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

早过忘川 提交于 2019-12-01 18:07:00
Nambi

It is a delimiter

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

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.

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.

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