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

How can I use a condition in explode() function?

这是我的代码:

$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", ....);

有什么想法吗?

@stack 尝试下面的概念,它将为您的特定字符串提供所需的输出:

<?php
$str = "this is a test";
$arr = strpos($str, "a") < strpos($str,"test") ? explode(" ", $str, 3) : explode(" ", $str);
print_r($arr);

你可以用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+

捕获数组中的给定单词或任何非 space 单词

您可以按 <space> 分割字符串,然后按预期加入它们。像这样:

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

// To split the string per <space>
$arr = explode(' ', $str);

// To remove empty elements
$arr = array_filter($arr);

foreach ( $arr as $k => $v) {
    if ( isset($arr[$k+1])) {
        $combined_word = $arr[$k] . ' ' . $arr[$k+1];
        if ( in_array($combined_word, $one_words) ){
            $arr[$k] = $combined_word;
            unset($arr[$k+1]);
        }
    }
}

print_r($arr);

Demo