为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕后森 2023-11-03 15:27:33
我正在搜索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
查看完整描述

1 回答

?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

您可以这样做:

  1. 删除所有可能影响将字符串分解为单个单词的标点符号等,并通过将所有非字母数字字符替换为空格来确保单词由空格分隔,例如一、二、三现在可以识别为 3 个单独的单词)

  2. 将输入字符串和脏话字符串转换为小写以便于比较

  3. 将两个字符串分解为数组(这是替换输入字符串中的空格很重要的地方!)

  4. 交叉数组以找到两者共有的单词

您可能还想考虑从输入字符串中删除数字,具体取决于您想要如何处理数字。

完整代码及详细注释如下:

// 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;


查看完整回答
反对 回复 2023-11-03
  • 1 回答
  • 0 关注
  • 92 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信