PHP 8.1.28 Released!

字符类(方括号)

左方括号开始一个字符类的描述,并以方中括号结束。 单独的一个右方括号没有特殊含义。如果一个右方括号需要作为一个字符类中的成员, 那么可以将它写在字符类的首字符处(如果使用了 ^ 取反, 那么是第二个)或者使用转义符。

一个字符类在目标字符串中匹配一个单独的字符; 该字符必须是字符类中定义的字符集合的其中一个, 除非使用了 ^ 对字符类取反。 如果^需要作为一个字符类的成员,确保它不是该字符类的首字符, 或者对其进行转义即可。

例如,字符类[aeiou]匹配所有的小写元音字母, 而[^aeiou]匹配所有非元音字母的字符。注意: ^只是一个通过枚举指定那些不存在字符类之中的字符的便利符号。而不是断言, 它仍然会从目标字符串中消耗一个字符,并且如果当前匹配点在目标字符串末尾, 匹配将会失败。

当大小写无关匹配被设置后,任意字符类都同时代表大小写两种版本,因此对于例子, 一个大小写不敏感的[aeiou]同时匹配"A"和"a", 并且大小写不敏感的[^aeiou]同时不匹配 "A"。

换行符在字符类中没有任何特殊涵义, 与 PCRE_DOTALLPCRE_MULTILINE 选项都无关。 例如 [^a] 这样的字符类始终会匹配换行符。

在字符类中,一个中划线(减号 -)可以用于指定从一个字符到另一个字符的范围。 比如,[d-m]匹配d到m之间的所有字符,这个集合时闭合的。 如果中划线自身要在一个字符类中描述, 它必须被转移或者出现在一个不会被解释为一个范围的位置, 典型的比如字符类开始或结束位置。

在一个字符范围描述后面不能使用右中括号。 比如一个模式 [W-]46] 被解释为一个包含 W 和 - 的字符类,后面紧跟字符串 ”46]”, 因此它可以匹配 ”W46]” 或 ”-46]”。然而, 如果中括号是经过转义的, 它将会被解释为范围的终点, 因此 [W-\]46] 就会被解释为一个单独的包含 W 至 ] 范围内所有字符以及 4、6 的字符类。 8 进制或 16 进制描述的中括号同样可以用于作为范围的终点。

范围操作以 ASCII 整理排序。它们可以用于为字符指定数值,比如 [\000-\037]。 如果在大小写不敏感匹配模式下使用一个包含字母的范围, 则同时匹配它的大小写形式。 比如 [W-c] 在不区分大小写匹配时等价于 [][\^_`wxyzabc],并且, 如果使用了 ”fr”(法国) 的地域设置字符表时, [\xc8-xcb] 将会在所有模式下匹配重音 E 字符。

字符类\d、\D、 \s、\S、\w 和 \W 也可以出现在一个字符类中, 用以将其匹配的字符类加入到新的自定义字符类中。比如, [\dABCDEF] 匹配任意合法的 16 进制数。用 ^ 可以很方便的制定严格的字符类, 比如 [^\W_] 匹配任何字母或数字,但不匹配下划线。

所有非字母数字字符除了\、-、 ^(在起始位置)以及结束的]在字符类中都是非特殊字符, 没有转义也不会有危害。模式结束符在表达式中总是特殊字符,必须进行转义。

Perl 支持 POSIX 字符类符号。这种字符类使用[::]闭合。 PCRE 同样支持这些字符类, 比如,[01[:alpha:]%]匹配 ”0”、“1”、任意字母或”%”。 支持的字符类如下:

字符类
alnum字母和数字
alpha字母
ascii0 - 127的ascii字符
blank空格和水平制表符
cntrl控制字符
digit十进制数(same as \d)
graph打印字符, 不包括空格
lower小写字母
print打印字符,包含空格
punct打印字符, 不包括字母和数字
space空白字符 (比\s多垂直制表符)
upper大写字母
word单词字符(和 \w 一样)
xdigit十六进制数字
空白字符有HT(9)、 LF(10)、VT(11)、 FF(12)、CR(13)、space(32)。 注意, 这个列表包含了垂直制表符。这使得space不同于\s, 因为它不包含垂直制表符(为了向 Perl 兼容)

[:word:]是一个 Perl扩展,[:blank:]是一个从 Perl5.8 中来的 GNU 扩展。 另外一个 Perl 扩展是取反,通过前置一个^。 比如, [12[:^digit:]] 匹配”1”, “2” 或任何非数字字符

在 UTF-8 模式中,大于 128 的字符值不会匹配任何 POSIX 字符类。 自 libpcre 8.10 起,某些字符类改为使用 Unicode 字符属性,所以不会出现提醒中的限制。 详情参阅 » PCRE(3) manual

Unicode character properties can appear inside a character class. They can not be part of a range. The minus (hyphen) character after a Unicode character class will match literally. Trying to end a range with a Unicode character property will result in a warning.

add a note

User Contributed Notes 4 notes

up
19
greaties at ghvernuft dot nl
2 years ago
From deep down the PCRE manual at http://www.pcre.org/pcre.txt :

\d any decimal digit
\D any character that is not a decimal digit
\h any horizontal white space character
\H any character that is not a horizontal white space character
\s any white space character
\S any character that is not a white space character
\v any vertical white space character
\V any character that is not a vertical white space character
\w any "word" character
\W any "non-word" character
up
3
Julian
1 year ago
Examples with Character classes

<?php

$stringA
= "1 In the beginning God created the heavens and the earth.";
$stringB = preg_replace('/[[:^alnum:]]/', '', $stringA); // string(46) "1InthebeginningGodcreatedtheheavensandtheearth"
$stringC = preg_replace('/[[:^alpha:]]/', '', $stringA); // string(45) "InthebeginningGodcreatedtheheavensandtheearth"
$stringD = preg_replace('/[[:^ascii:]]/', '', "Pokémon"); // string(6) "Pokmon"
$stringE = preg_replace('/[[:^blank:]]/', '*', $stringA); // string(57) "* ** *** ********* *** ******* *** ******* *** *** ******"
$stringF = preg_replace('/[[:blank:]]/', '-', $stringA); // string(57) "1-In-the-beginning-God-created-the-heavens-and-the-earth."

$stringG = sprintf("Vertical Tabulation: %s", chr(11)); // string(22) "Vertical Tabulation: "
$stringH = preg_replace('/[[:cntrl:]]/', '', $stringG); // string(21) "Vertical Tabulation: "
$stringLengthG = strlen($stringG); // int(22)
$stringLengthH = strlen($stringH); // int(21)

$stringI = preg_replace('/[[:digit:]]/', '', 'My age is 35'); //string(10) "My age is "
$stringJ = preg_replace('/[[:^digit:]]/', '', 'My age is 35'); // string(2) "35"

$stringK = preg_replace('/[[:^graph:]]/', '', $stringG); // string(19) "VerticalTabulation:"
$stringL = preg_replace('/[[:graph:]]/', '', $stringG); // string(3) " "

$stringM = preg_replace('/[[:lower:]]/', '', $stringG); // string(6) "V T: "
$stringN = preg_replace('/[[:^lower:]]/', '', $stringG); // string(16) "erticalabulation"

$stringO = preg_replace('/[[:^print:]]/', '', $stringG); // string(21) "Vertical Tabulation: "
$stringP = preg_replace('/[[:print:]]/', '', $stringG); // string(1) " "

$stringQ = preg_replace('/[[:punct:]]/', '', $stringG); // string(21) "Vertical Tabulation "
$stringR = preg_replace('/[[:^punct:]]/', '', $stringG); // string(1) ":"

$stringS = preg_replace('/[[:space:]]/', '', $stringG); // string(19) "VerticalTabulation:"
$stringT = preg_replace('/[[:^space:]]/', '', $stringG); // string(3) " "

$stringU = preg_replace('/[[:upper:]]/', '', $stringG); // string(20) "ertical abulation: "
$stringV = preg_replace('/[[:^upper:]]/', '', $stringG); // string(2) "VT"

$stringW = preg_replace('/[[:word:]]/', '', $stringG); // string(4) " : "
$stringX = preg_replace('/[[:^word:]]/', '', $stringG); // string(18) "VerticalTabulation"

$stringY = preg_replace('/[[:xdigit:]]/', '', 'abcdefghijklmnopqrstuvwxyz0123456789'); // string(20) "ghijklmnopqrstuvwxyz"
$stringZ = preg_replace('/[[:^xdigit:]]/', '', 'abcdefghijklmnopqrstuvwxyz0123456789'); // string(16) "abcdef0123456789"
up
6
wordragon at wrestingcontrol dot com
5 years ago
The documentation says:

"The character types \d, \D, \s, \S, \w, and \W may also appear in a character class, and add the characters that they match to the class."

It does not stress that other escape types may not. I wanted to split a string on either a comma (","), or a new line "\n". When my input stream began to include "\r\n", I decided to change "\n" to "\R". Unfortunately, my test string did not include a capital "R", or I might have found the problem sooner. My '/[\R,]/' was simply splitting on comma and the letter "R".

My test string...
"The Yum-Yum Company\r\n127 bernard street"

What DID work: '/(?:\R|,)+/'

["The Yum-Yum Company","127 bernard street"]

Given character classes only match one character, I can see clearly why my expectations were justifiably dashed, but hopefully this comment will save time for someone else.

I might add, this has taught me the value of PCRE_EXTRA (modifier "X"), which I have begun to use routinely now.
up
-8
php at delegated dot net
5 years ago
Some characters may not work as expected within a custom class. MS double quote for example is unrecognised when included in a class but is recognised otherwise.

ie:
<?php
preg_match_all
('/<a href=("|“)/')
?> will match but
<?php
preg_match_all
('/<a href=["“]/')
?> will not
when applied to <a href=“path">
To Top