如何从 PHP 字符串中的数组中查找准确的单词

我正在搜索stringan 中的一组单词,array以通知用户是否找到任何单词。但是,我得到的结果并不完全匹配。关于如何让它只显示完全匹配的任何想法。我的代码如下所示。


<?php


// Profanity check  

 $profaneReport = "";

 $allContent = "Rice Beans Class stite";

 $profanity_list = "lass tite able";


      $profaneWords = explode( ' ', $profanity_list );


      $wordsFoundInProfaneList = []; // Create words an array


      //search for the words;


      foreach ( $profaneWords as $profane ) {


        if ( stripos( $allContent, $profane ) !== false ) {


          $wordsFoundInProfaneList[ $profane ] = true;


        }


      }



    // check if bad words were found


      if ( $wordsFoundInProfaneList !== 0 ) {


         $profaneReportDesc = "Sorry, your content may contain such words as " . "<strong>" . implode( ", ", array_keys( $wordsFoundInProfaneList )) . '</strong>"';


      } else {


       $profaneReportDesc = "Good: No profanity was found in your content";


      }


     echo $profaneReportDesc;

  


?>

上面的代码返回“抱歉,您的内容可能包含诸如 lass, tite”这样的单词,当它们与中的单词不完全匹配时$allContent


慕后森
浏览 93回答 1
1回答

天涯尽头无女友

您可以这样做:删除所有可能影响将字符串分解为单个单词的标点符号等,并通过将所有非字母数字字符替换为空格来确保单词由空格分隔,例如一、二、三现在可以识别为 3 个单独的单词)将输入字符串和脏话字符串转换为小写以便于比较将两个字符串分解为数组(这是替换输入字符串中的空格很重要的地方!)交叉数组以找到两者共有的单词您可能还想考虑从输入字符串中删除数字,具体取决于您想要如何处理数字。完整代码及详细注释如下:// Profanity check  $profaneReport = "";$profanity_list = "hello TEN test commas";    $allContent = "Hello, world! This is a senTENce for testing. It has more than TEN words and contains some punctuation,like commas.";/* Create an array of all words in lowercase (for easier comparison) */$profaneWords = explode( ' ', strtolower($profanity_list) );/* Remove everything but a-z (i.e. all punctionation numbers etc.) from the sentence    We replace them with spaces, so we can break the sentence into words */$alpha = preg_replace("/[^a-z0-9]+/", " ", strtolower($allContent));/* Create an array of the words in the sentence */$alphawords = explode( ' ', $alpha );/* get all words that are in both arrays */$wordsFoundInProfaneList = array_intersect ( $alphawords, $profaneWords);// check if bad words were found, and display a message if ( !empty($wordsFoundInProfaneList)) {    $profaneReportDesc = "Sorry, your content may contain such words as " . "<strong>" . implode( ", ", $wordsFoundInProfaneList) . '</strong>"';} else {    $profaneReportDesc = "Good: No profanity was found in your content";}echo $profaneReportDesc;
打开App,查看更多内容
随时随地看视频慕课网APP