Reputation: 10961
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?
Upvotes: 10
Views: 8803
Reputation: 785621
As per PHP Manual on regex delimiters
A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.
So essentially there is no difference between using slash or @
or #
. However keep in mind that chosen delimiter must not appear in the regex itself otherwise you will need to escape that character.
Tip: Since PCRE allows any non-alphanumeric, non-backslash, non-whitespace
as delimiter, sometimes it is better to use control characters as delimiters when you can't predict the content of regex being used. See below example:
$repl = preg_replace('^K^foo^K', 'bar', 'foo.txt' );
Here this code is using a control character ^K
(typed as ctrl-V-K
on shell)
Upvotes: 7
Reputation: 799130
Using /
makes it harder to put a /
in the regex or replacement. Using @
makes it harder to put a @
in the regex or replacement. Other than that, there is no difference.
Upvotes: 3
Reputation: 51670
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]!"
Upvotes: 6
Reputation: 523534
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 /
.
Upvotes: 7