Sas*_*cha 4 php regex preg-match-all preg-match preg-split
几天来我一直在思考这个问题,但似乎没有什么能得到想要的结果。
例子:
$var = "Some Words - Other Words (More Words) Dash-Binded-Word";
Run Code Online (Sandbox Code Playgroud)
想要的结果:
array(
[0] => Some Words
[1] => Other Words
[2] => More Words
[3] => Dash-Bound-Word
)
Run Code Online (Sandbox Code Playgroud)
我能够使用 preg_match_all 使这一切正常工作,但随后“Dash-Bound-Word”也被分解了。试图将它与周围的空格匹配是行不通的,因为它会破坏除破折号外的所有单词。
我使用的 preg_match_all 语句(也打破了破折号绑定词)是这样的:
preg_match_all('#\(.*?\)|\[.*?\]|[^?!\-|\(|\[]+#', $var, $array);
Run Code Online (Sandbox Code Playgroud)
我当然不是 preg_match、preg_split 方面的专家,因此这里的任何帮助将不胜感激。
您可以使用一个简单的preg_match_all:
\w+(?:[- ]\w+)*
Run Code Online (Sandbox Code Playgroud)
看演示
\w+ - 1 个或多个字母数字或下划线(?:[- ]\w+)* - 0 个或多个...
[- ]- 连字符或空格(您可以将空格更改\s为匹配任何空格)\w+ - 1 个或多个字母数字或下划线$re = '/\w+(?:[- ]\w+)*/';
$str = "Some Words - Other Words (More Words) Dash-Binded-Word";
preg_match_all($re, $str, $matches);
print_r($matches[0]);
Run Code Online (Sandbox Code Playgroud)
结果:
Array
(
[0] => Some Words
[1] => Other Words
[2] => More Words
[3] => Dash-Binded-Word
)
Run Code Online (Sandbox Code Playgroud)