PHP正则表达式之分隔符

当使用PCRE函数的时候,需要使用分隔符将模式括起来。分隔符可以是除下列字符以外的其他字符:字母或数字,反斜杠,空白字符(non-alphanumeric, non-backslash, non-whitespace)。

经常使用的分隔符有:斜杠(/,forward slash),井号(#,hash sign)和波浪号(~,tilde)。下面这些是有效的模式:

/foo bar/   #^[^0-9]$#

+php+   %[a-zA-Z0-9_-]%

如果在模式中要使用到分隔符,则必须在其前面使用反斜杠。如果在模式中多处使用到分隔符,更好的处理方式是使用其他的字符作为分隔符,以增强模式的可读性。例如:

/http:\/\//   #http://#
 

Delimiters

When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

Often used delimiters are forward slashes (/), hash signs (#) and tildes (~). The following are all examples of valid delimited patterns.

/foo bar/
#^[^0-9]$#
+php+
%[a-zA-Z0-9_-]%

If the delimiter needs to be matched inside the pattern it must be escaped using a backslash. If the delimiter appears often inside the pattern, it is a good idea to choose another delimiter in order to increase readability.

/http:\/\//
#http://#

The preg_quote() function may be used to escape a string for injection into a pattern and its optional second parameter may be used to specify the delimiter to be escaped.

In addition to the aforementioned delimiters, it is also possible to use bracket style delimiters where the opening and closing brackets are the starting and ending delimiter, respectively.

{this is a pattern}

You may add pattern modifiers after the ending delimiter. The following is an example of case-insensitive matching:

#[a-z]#i

来源:http://www.php.net/manual/en/regexp.reference.delimiters.php

About 智足者富

http://chenpeng.info

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>