\s在PHP中匹配哪些空白字符?

7
PHP中转义序列\s匹配的完整字符列表是什么?一些正则表达式还包括垂直空格和其他字符在这个转义序列中。
3个回答

4

来自pcrepattern规范页面:

Generic character types

\s     any white space character

For compatibility with Perl, \s did not used to match the VT character (code 11), which made it different from the the POSIX "space" class. However, Perl added VT at release 5.18, and PCRE followed suit at release 8.34. The default \s characters are now HT (9), LF (10), VT (11), FF (12), CR (13), and space (32), which are defined as white space in the "C" locale. This list may vary if locale-specific matching is taking place. For example, in some locales the "non-breaking space" character (\xA0) is recognized as white space, and in others the VT character is not.

因此,\s将匹配5个字符以及更多的字符,具体取决于:

  1. PCRE库版本
  2. 区域设置

这个测试比较了各种PHP版本中preg_match的结果。


2
我也是在搜索列表时到达了这里。但页面可能已经更改。以下是列表: \s匹配的空格仅表示以下5个字符: 9 = 0x09 = 水平制表符, 10 = 0x0A = 换行符, 12 = 0x0C = 换页符, 13 = 0x0D = 回车符, 32 = 0x20 = 空格, http://www.php.net/manual/en/regexp.reference.escape.php - Satya Prakash

4

PHP有\h用于仅匹配水平空白字符:http://www.php.net/manual/en/regexp.reference.escape.php

根据http://www.pcre.org/pcre.txt

为了与Perl兼容,\s不匹配VT字符(代码11)。这使它与POSIX“空格”类不同。\s字符是HT(9),LF(10),FF(12),CR(13)和空格(32)。如果在Perl脚本中包含"use locale;",\s可能匹配VT字符。在PCRE中,它永远不会。

因此,如果“垂直空间”指的是垂直制表符,则答案是否定的。

序列\h、\H、\v和\V是在Perl 5.10发布时添加的功能。与其他序列相比,默认情况下只匹配ASCII字符,这些序列始终匹配UTF-8模式下的某些高值代码点,无论是否设置PCRE_UCP。
水平空格字符包括:
U+0009 水平制表符 U+0020 空格 U+00A0 不间断空格 U+1680 奥格姆空格标记 U+180E 蒙古语元音分隔符 U+2000 空格(等宽) U+2001 空格(等宽,半个em) U+2002 空格(等宽,1个em) U+2003 空格(等宽,1.5个em) U+2004 空格(等宽,2个em) U+2005 空格(等宽,2.5个em) U+2006 空格(等宽,3个em) U+2007 数字间隔空格 U+2008 标点间隔空格 U+2009 窄空格 U+200A 头发空格 U+202F 窄不间断空格 U+205F 中等数学空格 U+3000 表意空格
垂直空格字符包括:
U+000A 换行符 U+000B 垂直制表符 U+000C 换页符 U+000D 回车符 U+0085 下一行 U+2028 行分隔符 U+2029 段落分隔符

好的,http://www.pcre.org/pcre.txt 上说它不匹配垂直制表符 - 我不知道垂直空格是什么。 - Kobi
什么是水平空白字符? - Stephan
@Stephan - 我只是在思考同样的问题。请搜索http://www.pcre.org/pcre.txt文件中的“ The sequences \h,\H,\v和\V”。根据您的需求,“\h”可能更合适。 - Kobi
我已经使用水平和垂直字符列表编辑了您的帖子。 - Stephan

1

来自http://www.pcre.org/pcre.txt:

\s 匹配任何被 \p{Z} 匹配的字符, 还包括水平制表符、换行符、换页符、回车符


4
虽然引用正确,但这取决于编译时的设置。PHP 在该代码周围使用了 #ifdef PCRE_UCP。不应依赖它。 - mario

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接