这是我的示例字符串(该字符串有5个字;实际上,可能还有更多个字):
$str = "I want to filter it";
我想要的输出:
$output[1] = array("I","want","to","filter","it");
$output[2] = array("I want","want to","to filter","filter it");
$output[3] = array("I want to","want to filter","to filter it");
$output[4] = array("I want to filter","want to filter it");
$output[5] = array("I want to filter it");
我正在尝试:
$text = trim($str);
$text_exp = explode(' ',$str);
$len = count($text_exp);
$output[$len][] = $text; // last element
$output[1] = $text_exp; // first element
这给了我第一个和最后一个数组。如何获得所有中间阵列?
适用于任何长度单词的更通用的解决方案:
$output = array();
$terms = explode(' ',$str);
for ($i = 1; $i <= count($terms); $i++ )
{
$round_output = array();
for ($j = 0; $j <= count($terms) - $i; $j++)
{
$round_output[] = implode(" ", array_slice($terms, $j, $i));
}
$output[] = $round_output;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句