为什么PHP preg_ *函数需要regexp分隔符? [关闭]

This is bugging me:

Why preg_match('/pattern/', $haystack) instead of preg_match('pattern', $haystack)? Everything I've seen just states as a fact that they're necessary, and mentions that you can use alternate delimiters.

But, it's a function that defines its own interface outside of the string. It has a flags argument. Adding intra-string syntax seems capricious.

Is it something inherited from pcre that the authors were just not interested in working around? Yet another perverse fact of PHP? Or is there a justification?

The delimiters are for compatibility with Perl. Perl regular expressions use the delimiters, and rely on the end delimiter to signify the start of modifier flags, like i for case insensitivity, for example.

// Match alpha-numeric, case insensitive, multiline
preg_match('/^[a-z0-9]+$/im', $input);

The optional flags argument to preg_match() does not implement the regular expression flags like i that follow the second delimiter. They serve a different function, and indeed PREG_OFFSET_CAPTURE is the only flag available there. This is not to say the regex flags could not have been implemented as another function parameter. They certainly could have, but Perl-compatibility is the goal here.

PHP is not the only language that borrows directly from Perl to implement regular expressions. JavaScript does to some degree, and Ruby even implements Perl's =~ operator for regular expression matches.

I believe it was done for interoperability, so you can copy&paste pattern from/to another language and not having to convert pattern options to/from PHP flags.

The delimiter is for Perl compatibility (thus, Perl Compatible Regular Expressions, or PCRE). The pattern also includes any modifiers you choose to use, and they must be placed after the closing delimiter.

Is it something inherited?

The truth is every programming language needs a standard so PCRE is a better standard. click