几天来我一直在思考这个问题,但似乎没有得到想要的结果。
例子:
$var = "Some Words - Other Words (More Words) Dash-Binded-Word";
期望的结果:
array(
[0] => Some Words
[1] => Other Words
[2] => More Words
[3] => Dash-Bound-Word
)
我能够使用 preg_match_all 使这一切正常工作,但随后“Dash-Bound-Word”也被分解了。尝试将它与周围的空格匹配是行不通的,因为它会破坏除破折号之外的所有单词。
我使用的 preg_match_all 语句(它也分解了破折号绑定(bind)的词)是这样的:
preg_match_all('#\(.*?\)|\[.*?\]|[^?!\-|\(|\[]+#', $var, $array);
我当然不是 preg_match、preg_split 方面的专家,因此非常感谢您提供任何帮助。
最佳答案
您可以使用一个简单的preg_match_all
:
\w+(?:[- ]\w+)*
参见 demo
\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]);
结果:
Array
(
[0] => Some Words
[1] => Other Words
[2] => More Words
[3] => Dash-Binded-Word
)
关于PHP:如何用破折号和括号之间的所有内容拆分字符串。 (preg_split 或 preg_match),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32618065/