"this", 1-6ren">
gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:56:09 33 4
gpt4 key购买 nike

这是我的代码:

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

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

if the word of a is followed by the word of test, then consider them as one word.

所以这是预期的输出:

/* expected output:
array (
0 => "this",
1 => "is",
2 => a test
)

换句话说,我想要这样的东西:/a[ ]+test|[^ ]+/ .但我不能使用提到的模式作为 explode() 函数的替代方案。因为在现实中,有很多我需要关心的二分词。我的意思是我想将一系列单词视为一个单词:

$one_words("a test", "take off", "go away", "depend on", ....);

有什么想法吗?

最佳答案

您可以使用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]);

输出:

Array
(
[0] => this
[1] => is
[2] => a test
)

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

\b(?:' . implode('|', $one_words) . ')\b|\S+

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

\b(?:a test|take off|go away|depend on)\b|\S+

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

关于php - 如何在 explode() 函数中使用条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42801642/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com