Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regex delimiters, / vs. | vs. {} , what are the differences?

Tags:

regex

php

In the PHP manual of PCRE, http://us.php.net/manual/en/pcre.examples.php, it gives 4 examples of valid patterns:

  • /<\/\w+>/
  • |(\d{3})-\d+|Sm
  • /^(?i)php[34]/
  • {^\s+(\s+)?$}

Seems that / , | or a pair of curly braces can use as delimiters, so is there any difference between them?

like image 750
powerboy Avatar asked May 23 '10 17:05

powerboy


People also ask

What are delimiters 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 are the delimiters 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 does Preg_match mean in PHP?

Definition and Usage The preg_match() function returns whether a match was found in a string.

How do you match a space in regex?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.


2 Answers

No difference, except the closing delimiter cannot appear without escaping.

This is useful when the standard delimiter is used a lot, e.g. instead of

preg_match("/^http:\\/\\/.+/", $str);

you can write

preg_match("[^http://.+]", $str);

to avoid needing to escape the /.

like image 109
kennytm Avatar answered Sep 28 '22 04:09

kennytm


In fact you can use any non alphanumeric delimiter (excluding whitespaces and backslashes)

"%^[a-z]%"

works as well as

"*^[a-z]*"

as well as

"!^[a-z]!"
like image 40
nico Avatar answered Sep 28 '22 03:09

nico