tags:

views:

60

answers:

2

In the PHP manual of PCRE, http://us.php.net/manual/en/pcre.examples.php, it gives 4 examples of valid patterns:

  • /<\/\w+>/
  • |(\d{3})-\d+|Sm
  • /^(?i)php[34]/
  • {^\s+(\s+)?$}

Seems that / , | or a pair of curly braces can use as delimiters, so is there any difference between them?

A: 

No difference, except the closing delimiter cannot appear without escaping.

This is useful when the standard delimiter is used a lot, e.g. instead of

preg_match("/^http:\\/\\/.+/", $str);

you can write

preg_match("[^http://.+]", $str);

to avoid needing to escape the /.

KennyTM
@KennyTM - The manual does not mention the use of [], but it is valid, right?
powerboy
Oh, I know the answer now. "A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character." -- http://us.php.net/manual/en/regexp.reference.delimiters.php
powerboy
I don't think [^http://.+] would work because it would mistakenly match any character that is not one of h,t,p , etc. #^http://.+# or ~^http://.+~ would be fine though.
jkasnicki
@Kenny: that's a terrible, terrible example!
SilentGhost
Yes, seems that delimiters can be omitted if there is not modifiers. Kenny, can you edit your answer?
powerboy
@jkasnicki: http://www.ideone.com/NrB47
KennyTM
@powerboy the manual **does** mention the use of `[…]` as delimiters: *In addition to the aforementioned delimiters, it is also possible to use bracket style delimiters where the opening and closing brackets are the starting and ending delimiter, respectively.* [source](http://php.net/regexp.reference.delimiters)
salathe
Note that brackets can still be used in the normal way despite being used as regex delimiters: `preg_replace("[[fo]]", "x", "foo")` yields `xxx`. It's only "stray" closing brackets that have to be escaped. This is another feature that's copied from Perl.
Alan Moore
+1  A: 

In fact you can use any non alphanumeric delimiter (excluding whitespaces and backslashes)

"%^[a-z]%"

works as well as

"*^[a-z]*"

as well as

"!^[a-z]!"
nico
Whitespace characters, and backslash, are non-alphanumeric, however they aren't allowed as the delimiter.
salathe
@salathe: that's right, updated my answer
nico