基于具有所有组合的子字符串将字符串拆分为两个

时间:2014-07-16 09:20:50

标签: php

假设我有一个字符串:

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

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

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

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

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

2 个答案:

答案 0 :(得分:3)

$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.
    )
)

答案 1 :(得分: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
)