检查字符串是否包含数组中的单词 [英] Check if string contains word in array

查看:58
本文介绍了检查字符串是否包含数组中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个聊天页面.我有一个 $string = "这家伙是个卡车司机".我有一组坏词:$bads = array('truck', 'shot', etc).我如何检查 $string 是否包含 $bad 中的任何单词?
到目前为止,我有:

This is for a chat page. I have a $string = "This dude is a mothertrucker". I have an array of badwords: $bads = array('truck', 'shot', etc). How could I check to see if $string contains any of the words in $bad?
So far I have:

        foreach ($bads as $bad) {
        if (strpos($string,$bad) !== false) {
            //say NO!
        }
        else {
            // YES!            }
        }

除非我这样做,当用户在$bads 列表中输入一个单词时,输出为NO!其次是是!所以出于某种原因,代码运行了两次.

Except when I do this, when a user types in a word in the $bads list, the output is NO! followed by YES! so for some reason the code is running it twice through.

推荐答案

function contains($str, array $arr)
{
    foreach($arr as $a) {
        if (stripos($str,$a) !== false) return true;
    }
    return false;
}

这篇关于检查字符串是否包含数组中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆