dongshan2680 2014-03-25 04:24
浏览 38

如何检查单词是否在数组中然后返回匹配的单词

Question 1

I'm using the following to check for bad words from some input element, and i want to tell the user which word on their text is not allowed. How do i get that specific word or words from the array that matched it? And how when user entered more than one bad word this only detects the first word and ignores the rest.

Question 2.

How do i ignore lower and upper cases, this code doesn't recognize "John" and "john" as the same thing. I don't know if this is a regex job. Please reccomend another way if this is weak. PHP

$BadWords = array("James", "June", "Jane");
if (in_array($comment, $BadWords)){
    echo 'No way... that is not allowed lol...';
}

Question 3 (Speed)

Say i have around 2000 words to compare a word against, which way is the best to do this process faster without misuse resources while taking into account that filtering bad words is just an example as this is not limited to checking bad words and at all cases not considering databases.

Thanks.

  • 写回答

3条回答 默认 最新

  • drlhsfqoa350437979 2014-03-25 04:29
    关注

    Use the array_search to get the matched words from the key

     <?php
    $comment="James";
    $BadWords = array("James", "June", "Jane");
    $bwords = array_map('strtoupper',$BadWords);
    if (in_array(strtoupper($comment), $bwords)){
        $k=array_search($comment,$bwords);
        echo $BadWords[$k]."
    ";
        echo 'No way... that is not allowed lol...';
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启