【问题标题】:split a string into two based on a substring with all combinations基于具有所有组合的子字符串将字符串拆分为两个
【发布时间】:2014-07-16 09:20:49
【问题描述】:

假设我有一个字符串:

$test = "Amy and Babel are good friends, they went to play together and Babel got hurt."

现在,假设我想根据单词“Babel”(在此字符串中出现两次)拆分字符串

我的输出应该存储在一个数组中,包含所有可能的组合。例如,在这种情况下,数组元素包含

  • “Amy 和”,“是好朋友,他们一起去玩,Babel 受伤了。”
  • “Amy 和 Babel 是好朋友,他们一起去玩了”,“Babel 受伤了。”

我最初尝试使用explode("Babel", $test) 来获取所有相关的子字符串。我不知道如何以有效的方式将它们组合在一起。

【问题讨论】:

  • 我不确定将结果转换为我想要的数据结构的最有效方法是什么。

标签: php


【解决方案1】:
$inputText = "Amy and Babel are good friends, Babel being the little rascal, they went to play together and Babel got hurt.";
$explodeString = "Babel";
$exploded = explode($explodeString, $inputText);
$resultArray = array();
for($i = 0; $i < count($exploded)-1; ++$i) {
    $resultArray[$i] = array(implode($explodeString, array_slice($exploded, 0, $i+1)), implode($explodeString, array_slice($exploded, $i+1, (count($exploded)-1)-$i)));
}
print_r($resultArray);

这会导致:

Array
(
[0] => Array
    (
        [0] => Amy and 
        [1] =>  are good friends, Babel being the little rascal, they went to play together and Babel got hurt.
    )

[1] => Array
    (
        [0] => Amy and Babel are good friends, 
        [1] =>  being the little rascal, they went to play together and Babel got hurt.
    )

[2] => Array
    (
        [0] => Amy and Babel are good friends, Babel being the little rascal, they went to play together and 
        [1] =>  got hurt.
    )
)

【讨论】:

  • 它的代码相对容易阅读,但肯定有更多优化的可能性。对于explodeString 在inputText 中的出现次数每增加一次,就会发生另外2 个字符串连接操作,连接的字符串数量等于explodeString 在inputtext 中的出现次数。
【解决方案2】:

此链接可能对您有所帮助 http://php.net/manual/en/function.explode.php

<?php
$str = 'one|two|three|four';

// positive limit
print_r(explode('|', $str, 2));

// negative limit (since PHP 5.1)
print_r(explode('|', $str, -1));
?>

输出:

Array
(
    [0] => one
    [1] => two|three|four
)
Array
(
    [0] => one
    [1] => two
    [2] => three
)

【讨论】:

  • Explode 是肯定的答案,但正如 OP 已经说过的那样,他们已经使用过它。
  • @AndyHolmes : OP 被困在如何把它重新组合在一起......这实际上是一个令人困惑的线......把它放回字符串或 implode 后面!!!
  • @NoobEditor 我希望将结果存储在一个数组中,其中数组本身的每个元素都是一个数组,其中包含一个可能的组合,其中字符串被拆分为 2 个子字符串。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-03
  • 2011-06-14
  • 1970-01-01
  • 2018-08-03
  • 1970-01-01
  • 2023-01-26
相关资源
最近更新 更多