Why is the pattern string enclosed in forward slashes in php preg_match() function? Is it just a convention due to some historical reasons or part of the php syntax?
-
string enclosed in forward slashes it is your / his style can be anything but the character should not take place in regex, if so, this char must be escaped .. for my part, i use @ or pipe |donald123– donald1232015-02-03 11:42:56 +00:00Commented Feb 3, 2015 at 11:42
-
It's part of the regex syntax, not PHP - it's the same in Perl, and many other languages. Utilities such as sed use it too.halfer– halfer2015-02-03 11:48:12 +00:00Commented Feb 3, 2015 at 11:48
-
This question is a duplicate of Why do the PHP preg_* functions require regexp delimiters?Nic Wortel– Nic Wortel2015-02-16 14:16:35 +00:00Commented Feb 16, 2015 at 14:16
1 Answer
It is convention. In many languages (Javascript, Perl, ...) the slashes are a language construct to define a Regular Expression.
In PHP the pattern is always a string but it contains two parts. The expression itself and modifiers. The slashes enclose the expression to separate them from the modifiers. Any non-alphanumeric character is allowed for to be used as delimiter for the expression. You might see ^, ~, #, @ or others.
DELIMITER EXPRESSION DELIMITER MODIFIERS
/ .* / x
It is possible to use the brackets, too. Unlike other characters they can still be used in the expression the same way.
DELIMITER EXPRESSION DELIMITER MODIFIERS
( .* ) x
I suggest using () as delimiters because it reflects the match array.
preg_match('(.(.*))', 'FOO', $matches);
var_dump($matches);
Output:
array(2) {
[0]=>
string(3) "FOO"
[1]=>
string(2) "OO"
}