PHP:如何在字符串中找到任何长度的所有可能序列?

时间:2016-06-20 15:46:07

标签: php arrays string loops

我想获取用户输入(字符串)并将其转换为所有可能长度的单词组合(数组)列表,但只保留顺序组合。

因此,下面的PHP中列出的数组最终会显示为:

$newArray = ["this","string","will","be","chopped","up","this string","will be","be chopped","chopped up","this string will","string will be","be chopped up"];

我的代码(不工作)如下:

PHP

$str = "This string will be chopped up.";
$str = strtolower($str);
$strSafe = preg_replace("/[^0-9a-z\s-_]/i","",$str);
$array = explode(" ", $strSafe);
$newArray = [];
$newArrayEntry = [];

for($counter=0; $counter < COUNT($oneword); $counter++) {

    // List single words - as in array $oneword.
    echo "One word: ";
    echo $oneword[$counter];
    echo "<br />";

    $counterTwo = $counter+1;       

    if($counterTwo <= COUNT($oneword)) {
        $newArrayEntry[COUNT($newArrayEntry)] = $oneword[$counter];
        print "Adding counter One to newArray Entry: ".$oneword[$counter]."<br />";
        for($counterThree=($counter+1); $counterThree < $counterTwo; $counterThree++) {
            $newArrayEntry[COUNT($newArrayEntry)] = $oneword[$counterThree];

            if($counterThree - $counterTwo == 1) {
                $newArrayEntry[COUNT($newArrayEntry)] = $oneword[$counterTwo];
                print "Adding counter Two to newArrayEntry: ".$oneword[$counterTwo]."<br />";
            }
        }
        $newArrayString = join(' ', $newArrayEntry);
        $newArray[COUNT($newArray)] = $newArrayString;
    }
}

1 个答案:

答案 0 :(得分:2)

您可以使用此代码:

$str = "This string will be chopped up.";
$str = strtolower($str);
$strSafe = preg_replace("/[^0-9a-z\s-_]/i","",$str);
$array = explode(" ", $strSafe);
$newArray = [];

for ($len = 1; $len <= count($array); $len++) {
    for($start = 0; $start+$len <= count($array); $start++) {
        $newArray[] = implode(" ", array_slice($array, $start, $len));
    }
}   


var_export($newArray);  

输出:

array (
  0 => 'this',
  1 => 'string',
  2 => 'will',
  3 => 'be',
  4 => 'chopped',
  5 => 'up',
  6 => 'this string',
  7 => 'string will',
  8 => 'will be',
  9 => 'be chopped',
  10 => 'chopped up',
  11 => 'this string will',
  12 => 'string will be',
  13 => 'will be chopped',
  14 => 'be chopped up',
  15 => 'this string will be',
  16 => 'string will be chopped',
  17 => 'will be chopped up',
  18 => 'this string will be chopped',
  19 => 'string will be chopped up',
  20 => 'this string will be chopped up',
)