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

时间:2017-03-15 05:21:02

标签: php regex function conditional explode

这是我的代码:

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

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

  

如果a的单词后跟test的单词,则将其视为一个单词。

所以这是预期的输出:

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

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

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

有什么想法吗?

3 个答案:

答案 0 :(得分: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]);

<强>输出:

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+

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

答案 1 :(得分:1)

您可以按<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

答案 2 :(得分:-2)

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

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