tags:

views:

1010

answers:

3

Why do PHP regexes have the surrounding delimiters? It seems like it would be more clear if any pattern modifiers were passed in as a parameter to whatever function was being used.

A: 

There is no technical reason why it has to be like this.

As noted in a comment, the underlying library does not require that flags be passed as part of the regexp - in fact, the extension has to strip these off and pass them as a separate argument.

It appears as though the original implementer was trying to make it look like grep/sed/awk/perl/etc so that it is more familiar to programmers coming from those tools.

Cal
PCRE does not allow the surrounding delimiters at all. The PHP preg functions strip them off before passing them to the PCRE library.
Jan Goyvaerts
wow, then it's all sheer trying-to-be-perl? i'd been forgiving the syntax for years, but now i'm free to truly hate it. thanks!
Cal
This answer is fine for personal opinion, but it is not correct.
dreftymac
+9  A: 

The reason for the delimiter is to put flags after the pattern. Arguably flags could be passed as a separate parameter (Java can do it this way) but that's the way Perl did it originally (and sed/awk/vi before it) so that's how it's done now.

Don't use forward slashes: they're too common. Personally I nearly always use the ! character. I'm hardly ever looking for that.

cletus
Note: Java can also include flags within the regexp, at its beginning (?m) for multi-line for instance. (?s) for dotall, (?ms) for both, and so on.
VonC
@VonC, so can Python.
Evan Fosmark
So can Perl, PCRE, and even PHP's preg functions. But the preg functions have some extra flags that can only be specified after the regex.
Jan Goyvaerts
By "too common", do you mean too likely to appear within the pattern?
outis
+2  A: 

I don't know what the motives of the developers of the preg functions were. The only reason I can think of is that they tried a little too hard to do things the Perl way.

While the delimiters allow flags to be specified along with the regex as one parameter, specifying the flags as a separate parameter is much cleaner. That's how every other regular expression library (for languages that don't support literal regexes as a language feature) I know does it, including the PCRE library that PHP's preg functions are based on. The preg code indeed has to go trough the trouble of removing the regex delimiters from the string with your regex before it can be passed to PCRE.

Jan Goyvaerts