tags:

views:

65

answers:

2

The pipe symbol | is used in Regular Expression as a sort of 'either' statement, far as I know. Either this, either that, or that, or that, etc...

However, I wish to check a string with a regular expression, for the presence of this symbol. I've tried escaping it, but that doesn't seem to work.

How do I do this, especially if I'm already checking for a number of symbols to be present, like #, &, @, etc...

+4  A: 

Escaping that character is the right way. But make sure that you escape the escape characters in your string declaration as well:

"\\|"
'\\|'

Another way would be to use a character class ([|]) since in there you only have the characters ], ^ (only at the start), -, the escape character \ itself and the delimiter that have a special meaning and thus need to be escaped if meant to be expressed as plain characters.

Gumbo
And the caret character ^ only has special meaning if it is the first character in a character class, i.e. [^|] and [|^] will behave differently.
Rob Wells
+3  A: 
$ cat 1933190.php

<?php
    echo preg_match("/\|/", "This is not a pipe.") . "\n";
    echo preg_match("/\|/", "The | the | this is a |.") . "\n";
?>

Output:

$ php 1933190.php
0
1
The MYYN
Thanks for the clear example.
WebDevHobo
Why 1933190.php?
Alix Axel