任何人都可以向我解释如何使用preg_split()函数?我不明白这样的模式参数"/[\s,]+/".
例如:
我有这个主题:is is.我希望结果如下:
array (
0 => 'is',
1 => 'is',
)
Run Code Online (Sandbox Code Playgroud)
所以它会忽略空间和全程,我怎么能这样做?
Maj*_*nko 32
preg意味着P cre REG exp",这是多余的,因为"PCRE"意味着"Perl Compatible Regexp".
Regexps对初学者来说是一场噩梦.我仍然不完全理解他们,我已经和他们一起工作多年了.
基本上你在那里的例子,分解是:
"/[\s,]+/"
/ = start or end of pattern string
[ ... ] = grouping of characters
+ = one or more of the preceeding character or group
\s = Any whitespace character (space, tab).
, = the literal comma character
Run Code Online (Sandbox Code Playgroud)
所以你有一个搜索模式,"在字符串的任何部分上拆分,至少有一个空白字符和/或一个或多个逗号".
其他常见字符是:
. = any single character
* = any number of the preceeding character or group
^ (at start of pattern) = The start of the string
$ (at end of pattern) = The end of the string
^ (inside [...]) = "NOT" the following character
Run Code Online (Sandbox Code Playgroud)
对于PHP ,官方文档中有很好的信息.
这应该工作:
$words = preg_split("/(?<=\w)\b\s*[!?.]*/", 'is is.', -1, PREG_SPLIT_NO_EMPTY);
echo '<pre>';
print_r($words);
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)
输出将是:
Array
(
[0] => is
[1] => is
)
Run Code Online (Sandbox Code Playgroud)
在我解释正则表达式之前,只需要解释一下PREG_SPLIT_NO_EMPTY.这基本上意味着只返回preg_split结果不为空的结果.这可以确保数组中返回的数据$words确实包含数据,而不仅仅是在处理正则表达式模式和混合数据源时可能发生的空值.
并且可以使用此工具将此正则表达式的解释分解为:
NODE EXPLANATION
--------------------------------------------------------------------------------
(?<= look behind to see if there is:
--------------------------------------------------------------------------------
\w word characters (a-z, A-Z, 0-9, _)
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char
--------------------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
[!?.]* any character of: '!', '?', '.' (0 or more
times (matching the most amount possible))
Run Code Online (Sandbox Code Playgroud)
通过/(?<=\w)\b\s*[!?.]*/在其他其他工具中输入完整的正则表达式模式,可以找到更好的解释:
(?<=\w) 积极的Lookbehind - 断言下面的正则表达式可以匹配\w 匹配任何单词字符 [a-zA-Z0-9_]\b 在单词边界断言位置 (^\w|\w$|\W\w|\w\W)\s* 匹配任何空格字符 [\r\n\t\f ]!?.!?.字面上的单个字符最后一个正则表达式的解释可以被一个人 - 也称为我 - 归结为如下:
匹配 - 分割 - 在单词边界之前出现的任何单词字符,可以有多个空格和标点符号!?..
| 归档时间: |
|
| 查看次数: |
45257 次 |
| 最近记录: |