我有像这样的代码
$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'
...
)
答案 0 :(得分:0)
在删除列入黑名单的单词和构建单词对数组时,你的内容过于复杂。
删除黑名单:
$inputWords = mb_split('\s+', 'If you want to have a preformatted block...');
$forbiddenWords = array("want", "have");
$filtered = array_diff($inputWords, $forbiddenWords); // removes blacklisted
将每2个已过滤的单词加入字符串:
$pairs = array_chunk($filtered, 2); // array of arrays
$pairs = array_map(function($a) { return implode(' ', $a); }, $pairs);
<强> See it in action 强>