如何在explode()函数中使用条件?

sta*_*ack 3 php regex conditional function explode

这是我的代码:

$str = "this is a test"
$arr = explode(' ', $str);
/* output:
array (
    0 => "this",
    1 => "is",
    2 => a,
    3 => test
)
Run Code Online (Sandbox Code Playgroud)

我要做的就是将这个条件添加到explode()函数中:

如果单词a后跟单词of test,则将它们视为一个单词.

所以这是预期的输出:

/* expected output:
array (
    0 => "this",
    1 => "is",
    2 => a test
)
Run Code Online (Sandbox Code Playgroud)

换句话说,我想要这样的事情:/a[ ]+test|[^ ]+/.但我不能使用提到的模式作为explode()功能的替代品.因为实际上,我需要关注许多双字词.我的意思是有一系列单词我想被视为一个单词:

$one_words("a test", "take off", "go away", "depend on", ....);
Run Code Online (Sandbox Code Playgroud)

任何的想法?

anu*_*ava 5

您可以使用implode加入所有保留字并使用它,preg_match_all如下所示:

$str = "this is a test";
$one_words = array("a test", "take off", "go away", "depend on");

preg_match_all('/\b(?:' . implode('|', $one_words) . ')\b|\S+/', $str, $m); 
print_r($m[0]);
Run Code Online (Sandbox Code Playgroud)

输出:

Array
(
    [0] => this
    [1] => is
    [2] => a test
)
Run Code Online (Sandbox Code Playgroud)

我们正在使用的正则表达式是这样的:

\b(?:' . implode('|', $one_words) . ')\b|\S+
Run Code Online (Sandbox Code Playgroud)

对于数组中的给定值,它将有效:

\b(?:a test|take off|go away|depend on)\b|\S+
Run Code Online (Sandbox Code Playgroud)

这基本上是捕获数组中的给定单词或使用任何非空格单词 \S+