-2

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?

3
  • 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 | Commented 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. Commented Feb 3, 2015 at 11:48
  • This question is a duplicate of Why do the PHP preg_* functions require regexp delimiters? Commented Feb 16, 2015 at 14:16

1 Answer 1

2

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"
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.