假设我有一个字符串,如下所示:
$string = 'president barack obama';
现在,假设我想把它分解成一个数组,打破这些词。你认为我可以使用explode()
,对吗?这是有效的,但如果我想要一系列所有可能的从左到右的单词组合怎么办?像这样:
Array
(
[0] => 'barack'
[1] => 'barack obama'
[2] => 'obama'
[3] => 'president'
[4] => 'president barack'
[5] => 'president barack obama'
)
最有效的方法是什么?
到目前为止,我已经想出了一个可能的解决方案,但我希望你们中的一个能给我一个更好的主意。我想像这样接近这个:
$current_word . ' ' . $new_word;
组成的新数组值。为每个单词执行此操作。现在,这可能会奏效。然而,它似乎很烦人,我担心其他人可能有更好的方法来做到这一点。你们都推荐什么?或许,是否有一个我不知道的PHP功能呢?
答案 0 :(得分:5)
这应该可以满足您的需求:
$string = 'president barack obama won';
$results = getWordPermutaions($string);
print_r($results);
function getWordPermutaions($inStr) {
$outArr = Array();
$tokenArr = explode(" ", $inStr);
$pointer = 0;
for ($i=0; $i<count($tokenArr); $i++) {
$outArr[$pointer] = $tokenArr[$i];
$tokenString = $tokenArr[$i];
$pointer++;
for ($j=$i+1; $j<count($tokenArr); $j++) {
$tokenString .= " " . $tokenArr[$j];
$outArr[$pointer] = $tokenString;
$pointer++;
}
}
return $outArr;
}
/*
$results:
Array (
[0] => 'president'
[1] => 'president barack'
[2] => 'president barack obama'
[3] => 'president barack obama won'
[4] => 'barack'
[5] => 'barack obama'
[6] => 'barack obama won'
[7] => 'obama'
[8] => 'obama won'
[9] => 'won'
)
*/
答案 1 :(得分:3)
另一个有效的解决方案:
$s = 'president barack obama won';
function myExplode($s) {
$ex = explode(" ", $s);
$ec = 0;
$x = 0;
foreach ($ex as $word) {
$rs = isset($res) ? sizeof($res) : 0;
if ($rs > 0)
for ($i=$ec-$x; $i < $rs; $i++) $res[] = "{$res[$i]} {$word}";
$x++;
$res[] = $word;
$ec = sizeof($res);
}
return isset($res) ? $res : false;
}
print_r( myExplode($s) );
<强>输出强>
Array
(
[0] => president
[1] => president barack
[2] => barack
[3] => president barack obama
[4] => barack obama
[5] => obama
[6] => president barack obama won
[7] => barack obama won
[8] => obama won
[9] => won
)