【发布时间】:2016-06-20 15:46:06
【问题描述】:
我想获取用户输入(字符串)并将其转换为所有可能长度的单词组合(数组)列表,但只保留按顺序排列的组合。
所以下面 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;
}
}
【问题讨论】:
-
“字符串将”丢失...
-
您可以使用 push 将值添加到您的数组中......并且在计数器循环中,您需要另一个计数器,据我所知,它可以从不同的点和不同的地方循环遍历您的基本数组长度。
-
谢谢梅达!不知道你的意思是什么。
-
我的意思是您在所需的输出中拥有
....."this string","will be"....,但从逻辑上讲,"string will",应该出现在这两个值之间。