我在 PHP 中使用 preg_split 函数来创建一个包含多个不同元素的数组。但是,我想排除一个恰好包含我 preg_splitting 的元素之一的字符串。
$array['stuff'] = preg_split('/\[#]|\ & |\ & |\& |\&|\ &|\ > |\ > |\> |\>|\ >|\ & |\ & |\& |\&|\ &|\ \/ |\ \/ |\\/ |\\/|\ \/|\ > |\ > |\> |\>|\ >|\ , |\ , |\, |\,|\, |\ :: |\ :: |\:: |\ ::|\::|\ ::|\ : |\ : |\: |\:|\ :|\ - |\ - |\- |\-|\ -/', $array['stuff'] ) ;
我想要做的是将诸如“foo-bar”之类的字符串排除在拆分匹配之外,因为它包含破折号。 “foo-bar”需要与我的目的完全匹配。
最佳答案
生成的正则表达式将非常复杂,特别是如果您有很多像“foo-bar”这样的异常。
您应该使用条件子模式,其中lookbehind作为条件,lookahead作为其yes模式:
$res = preg_split('/(?(?<=foo)\-(?!bar)|\-)/', 'aasdf-fafsdf-foo-bar-asdf' );
var_dump( $res );
结果:
array(4) {
[0]=>
string(5) "aasdf"
[1]=>
string(6) "fafsdf"
[2]=>
string(7) "foo-bar"
[3]=>
string(4) "asdf"
}
让我解释一下这里发生了什么。 \-
表示
Match any dash character.
但我们想要的是
Match any dash character that is not part of foo-bar.
由于我们无法在正则表达式中实现它,因此我们对其进行了一些更改:
Match any dash character that if preceded by foo is not followed by bar.
为了实现 if 部分,我们使用条件子模式,语法如下:
(?(condition)yes-pattern|no-pattern)
我们的“条件”将是“前面是 foo”,以检查我们是否使用了后向查找:
(?<=foo)
如果这是真的,我们应该寻找“后面没有横线的破折号”,以便我们使用否定的前瞻:
\-(?!bar)
这成为我们的“是模式”。我们的“无模式”应该是 \-
或“任意破折号”。完整的正则表达式是:
(?(?<=foo)\-(?!bar)|\-)
更新:要将其合并到当前的正则表达式中,请在末尾更改此部分:
|\ - |\ - |\- |\-|\ -/
至
|\s?(?(?<=foo)\-(?!bar)|\-)\s?/
关于php - 当字符串已经包含 PHP 中的可分割字符时,如何从 preg_split 中排除字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6967752/