PHP:如何用破折号和括号之间的所有内容拆分字符串。 (preg_split 或 preg_match)

标签 php regex preg-match preg-match-all preg-split

几天来我一直在思考这个问题,但似乎没有得到想要的结果。

例子:

$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 个或多个字母数字或下划线

IDEONE demo :

$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/

相关文章:

php - 有没有办法设置一个类变量以应用于 php 中该类的所有实例?

regex - Perl 文件逐行读取 (RegEx)

regex - Golang替换不在引号之间的所有空格

php - 如何在 PHP 中使用 filemtime 函数?

PHP RESTful CRUD 框架

javascript - 如何防止正则表达式匹配 javascript 中的所有其他匹配项

php - Preg_match 从一些数字中删除最后的零

php - 正则表达式匹配第一个单词与最后一个单词相同

php - 如何从 php 中的用户输入中删除 http、https、slash、www

php - 如何将带有HTML实体和无效字符的文本转换为其等效的UTF-8?