我想获取用户输入(字符串)并将其转换为所有可能长度的单词组合(数组)列表,但只保留顺序组合。
因此,下面的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;
}
}
答案 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',
)