What does the “~” character signify in PHP regex?

孤街浪徒 提交于 2019-12-04 03:28:37

问题


What does the "~" character mean in the following?:

preg_match_all("~<img [^>]+>~", $inputw, $output);

My guess is that they are beginning and end markers such as ^ and $.


回答1:


It is a delimiter

A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.




回答2:


As Nambi said you are free to choose the delimiter in a regex. However if the delimiter appears in the pattern it has to escaped. Knowing this, imagine the following situation

'/\/var\/www\/test/' # delimited with /
'~/var/www/test~' # delimited with ~

The last one does not require to escape the / as the delimiter is now ~. Much cleaner isn't it?

As a general guideline you are encouraged to choose a delimiter which isn't pattern of the pattern itself, I guess ~ is widely distributed as an alternative to / as it rarely appears in real world pattern.




回答3:


The dirty little delimiter secret they don't tell you ->
http://uk.php.net/manual/en/regexp.reference.delimiters.php

Examples:

Paired delimiters (raw: \d{2}Some\{33\}\w{5})

{\d{2}Some\\{33\\}\w{5}} parses to \d{2}Some\\{33\\}\w{5} and
{\d{2}Some\{33\}\w{5}} parses to \d{2}Some{33}\w{5}

Un-Paired delimiters (raw: \d{2}Some\+33\+\w{5})

+\d{2}Some\+33\+\w{5}+ parses to \d{2}Some+33+\w{5} and
+\d{2}Some\\+33\\+\w{5}+ won't parse because the delimiter is un-escaped.



来源:https://stackoverflow.com/questions/21624545/what-does-the-character-signify-in-php-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!