0

我有这样的代码

$words2= 'If you want to have a preformatted block within a list, indent by eight spaces.';

$forbiddenwords=array("word1","word2");

foreach($words2 as $b=>$v)
{
    if(in_array($v, $forbidden) ){
    unset($words2[$b] );

    }
}

$words2 = array_values($words2);

$words2=implode(' ',$words2);

$words2 = implode(' ',array_chunk(mb_split('\s', $words2), 2));

echo "<pre>";
print_r($words2);
echo "</pre>";

我想要的是创建一个数组,它的每个值都包含字符串中的 2 个单词。上面的代码不起作用-implode() 不适用于关联数组-我想要的结果也是这样

array (
$words2[0]=>'If you'
$words2[1]=>'you want'
$words2[1]=>'want to'
...
)
4

1 回答 1

0

You are over-complicating things, both when removing blacklisted words and when constructing the arrays of pairs of words.

To remove blacklisted:

$inputWords = mb_split('\s+', 'If you want to have a preformatted block...');
$forbiddenWords = array("want", "have");

$filtered = array_diff($inputWords, $forbiddenWords); // removes blacklisted

To join every 2 filtered words into a string:

$pairs = array_chunk($filtered, 2); // array of arrays
$pairs = array_map(function($a) { return implode(' ', $a); }, $pairs);

See it in action.

于 2013-05-18T22:06:25.510 回答