【问题标题】:How can I use a condition in explode() function?如何在explode() 函数中使用条件?
【发布时间】:2017-08-05 17:06:22
【问题描述】:

这是我的代码:

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

有什么想法吗?

【问题讨论】:

  • 你问题的最后一句话让我很困惑。听起来preg_split 是你在那之前想要的。
  • downvoter,请发表评论并解释我的问题有什么问题?

标签: php regex function conditional explode


【解决方案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

【讨论】:

  • 我的回答呢?你不觉得会更简单吗?
  • 它应该可以工作++,但不确定它是否会更快/更简单。
  • @RizwanM.Tuman 您的答案基于a。正如我在问题中提到的,有很多分词 (即depend on) 应该被视为一个词。我的意思是你的方法行不通3v4l.org/UILv1
  • @stack 是的,这是真的......我错过了后面的部分,或者可能是后来编辑的 :)
【解决方案2】:

您可以使用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+捕获数组中的给定单词或任何非空格单词

【讨论】:

  • 如果数组包含let's party! 之类的内容,这将如何表现?可能不太可能,但以防万一。
  • let's party 也将像本例中的 a test 一样被单独捕获。
  • 如果数组增长到 1000 项,这将如何表现?还有$str 包含100 万字? (会不会够快?)
  • 我没有对大量输入进行基准测试,因为问题都是关于在分解/拆分中使用条件。我想说,任何基于正则表达式的解决方案或字符串搜索例程在搜索 tera 字节的数据时都会变得有点慢。
  • 我明白了,谢谢,点个赞……你觉得我的回答怎么样?
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 2020-06-15
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多