比较两个数组的元素 php
Compare elements of two arrays php
所以我有两个数组:
$badwords = array('bad-word', 'some-racist-term', 'nasty', 'bad-language');
$inputphrases = array('this-is-sentence-with-bad-word', 'nothing-bad-here', 'more-clean-stuff', 'this-is-nasty', 'this-contains-some-racist-term', 'one-more-clean', 'clean-clean', 'contains-bad-language');
我需要将输入短语数组的元素与坏词数组进行比较,并输出包含不带坏词的短语的新数组,如下所示:
$outputarray = array('nothing-bad-here', 'more-clean-stuff','one-more-clean', 'clean-clean');
我试着用两个 foreach 循环来做这件事,但它给了我相反的结果,也就是它输出了带有坏词的短语。
这是我尝试输出相反结果的代码:
function letsCompare($inputphrases, $badwords)
{
foreach ($inputphrases as $inputphrase) {
foreach ($badwords as $badword) {
if (strpos(strtolower(str_replace('-', '', $inputphrase)), strtolower(str_replace('-', '', $badword))) !== false) {
$result[] = ($inputphrase);
}
}
}
return $result;
}
$result = letsCompare($inputphrases, $badwords);
print_r($result);
这不是一个干净的解决方案,但希望您能了解正在发生的事情。不要犹豫,要求许可。 repl.it link
$inputphrases = array('this-is-sentence-with-bad-word', 'nothing-bad-here', 'more-clean-stuff', 'this-is-nasty', 'this-contains-some-racist-term', 'one-more-clean', 'clean-clean', 'contains-bad-language');
$new_arr = array_filter($inputphrases, function($phrase) {
$badwords = array('bad-word', 'some-racist-term', 'nasty', 'bad-language');
$c = count($badwords);
for($i=0; $i<$c; $i++) {
if(strpos($phrase, $badwords[$i]) !== false){
return false;
}
}
return true;
});
print_r($new_arr);
所以我有两个数组:
$badwords = array('bad-word', 'some-racist-term', 'nasty', 'bad-language');
$inputphrases = array('this-is-sentence-with-bad-word', 'nothing-bad-here', 'more-clean-stuff', 'this-is-nasty', 'this-contains-some-racist-term', 'one-more-clean', 'clean-clean', 'contains-bad-language');
我需要将输入短语数组的元素与坏词数组进行比较,并输出包含不带坏词的短语的新数组,如下所示:
$outputarray = array('nothing-bad-here', 'more-clean-stuff','one-more-clean', 'clean-clean');
我试着用两个 foreach 循环来做这件事,但它给了我相反的结果,也就是它输出了带有坏词的短语。 这是我尝试输出相反结果的代码:
function letsCompare($inputphrases, $badwords)
{
foreach ($inputphrases as $inputphrase) {
foreach ($badwords as $badword) {
if (strpos(strtolower(str_replace('-', '', $inputphrase)), strtolower(str_replace('-', '', $badword))) !== false) {
$result[] = ($inputphrase);
}
}
}
return $result;
}
$result = letsCompare($inputphrases, $badwords);
print_r($result);
这不是一个干净的解决方案,但希望您能了解正在发生的事情。不要犹豫,要求许可。 repl.it link
$inputphrases = array('this-is-sentence-with-bad-word', 'nothing-bad-here', 'more-clean-stuff', 'this-is-nasty', 'this-contains-some-racist-term', 'one-more-clean', 'clean-clean', 'contains-bad-language');
$new_arr = array_filter($inputphrases, function($phrase) {
$badwords = array('bad-word', 'some-racist-term', 'nasty', 'bad-language');
$c = count($badwords);
for($i=0; $i<$c; $i++) {
if(strpos($phrase, $badwords[$i]) !== false){
return false;
}
}
return true;
});
print_r($new_arr);