亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從 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 關注
  • 126 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號