首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在字符串中找到任意长度的所有可能序列?

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

Stack Overflow用户
提问于 2016-06-20 15:46:06
回答 1查看 106关注 0票数 0

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

因此,下面的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"];

我的代码(不起作用)如下:

代码语言:javascript
复制
$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;
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-20 21:38:41

您可以使用以下代码:

代码语言:javascript
复制
$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);  

输出:

代码语言:javascript
复制
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',
)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37926650

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档