Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regex delimiter, what's the point?

Tags:

regex

php

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.

like image 925
Evan Fosmark Avatar asked Jan 27 '09 05:01

Evan Fosmark


People also ask

What do delimiters do in regex?

Delimiters. The first element of a regular expression is the delimiters. These are the boundaries of your regular expressions. The most common delimiter that you'll see with regular expressions is the slash ( / ) or forward slash.

What is meant by delimiter?

A delimiter is a sequence of one or more characters for specifying the boundary between separate, independent regions in plain text, mathematical expressions or other data streams. An example of a delimiter is the comma character, which acts as a field delimiter in a sequence of comma-separated values.

What is meant by delimiter in PHP?

A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character. Leading whitespace before a valid delimiter is silently ignored. Often used delimiters are forward slashes ( / ), hash signs ( # ) and tildes ( ~ ).

What is a string delimiter?

In computer programming, a delimiter is a character that identifies the beginning or the end of a character string (a contiguous sequence of characters). The delimiting character is not part of the character string.


2 Answers

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.

like image 193
cletus Avatar answered Oct 25 '22 16:10

cletus


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.

like image 23
Cal Avatar answered Oct 25 '22 15:10

Cal