[英]Get 2 words in every array value
I have code like this one 我有这样的代码
$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>";
What I want is to create an array that every value of it contain 2 words from the string. 我想要的是创建一个数组,该数组的每个值都包含来自字符串的2个单词。 The code above doesn't work -implode() not working with associative arrays- also the result that I'm trying to have is like that
上面的代码不起作用-implode()不与关联数组一起工作-我想要的结果也像这样
array (
$words2[0]=>'If you'
$words2[1]=>'you want'
$words2[1]=>'want to'
...
)
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.