mrverdantgreen
mrverdantgreen

Reputation: 41

What are colons for in a preg_match pattern?

In the following PHP code (not mine):

$has_trailing_slash = preg_match(':/$:', $string);

what is the purpose of the colons? If I remove them, then the preg_match call complains if there isn't a trailing slash in the string. With the colons, preg_match doesn't complain if there isn't a trailing slash. So apparently the colons are some kind of conditional or optional indicator, but is this documented anywhere? I can't find one word of documentation about using colons this way with preg_match, or regex in general.

Upvotes: 1

Views: 716

Answers (3)

Jerry
Jerry

Reputation: 71578

The colons here are used as delimiters.

You need to use delimiters for a regex in PHP so that the regex engine can know where the regex starts and where the regex ends, and this is excluding the quotes you use in the function.

This is particularly important so that the regex engine can distinguish between the actual regular expression and the flags (if any) to be used (e.g. i (for case insensitive matching), s (to make dot match newlines), u (to allow unicode character matching), etc)

You can use a variety of delimiters and you can use a 'suitable' one depending on the situation. For instance, the most common delimiter to use is the forward slash: /. When you use the forward slash as delimiter, you will have to escape the forward slashes in the regular expression (by using a backslash).

Otherwise, you can change the delimiter itself and this said, you can use a a delimiter such as #, or ! or | or ~ or {} and so on, as long it's not alphanumeric or a backslash.

This means you can use:

preg_match(':/$:', $string);
preg_match('"/$"', $string);
preg_match('@/$@', $string);
preg_match('{/$}', $string);

But if you use /, you'll have to escape any / in the regex like so:

preg_match('/\/$/', $string);   # Either use a backslash
preg_match('/[/]$/', $string);  # Or wrap it around square brackets

Or even something as weird as this:

preg_match('\'/$\'', $string);

Using that would most likely confuse people reading your code and regex can be considered to be confusing enough!

Conclusion, you have a wide variety of delimiters to choose from, but it's preferable if you are consistent and try not to make your code confusing.

Upvotes: 3

ErickBest
ErickBest

Reputation: 4692

: are delimeters... php is flexible, you could use several Symbols to stand as delimiters to avoid escaping.

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213311

I guess those are delimiters. Replacements for /, since there is a / in your regex pattern. So, using / will require to to escape it. To avoid the escaping, you can use a different delimiter.

So, even these are valid - #/$#, !/$!, ~/$~, ...

Upvotes: 3

Related Questions