简体   繁体   中英

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

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?

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

This is useful when the standard delimiter is used a lot, eg instead of

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

you can write

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

to avoid needing to escape the / .

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]!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM