我在string中搜索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中的单词不完全匹配时。
发布于 2020-08-27 05:46:41
为了帮助其他用户寻找类似问题的答案,并在Alex Howansky's comment的基础上添加更多的输入字符串准备,以便更容易地将其转换为一系列单词,您可以这样做:
共有的单词
您可能也需要考虑从输入字符串中移除数字,具体取决于处理数字的方式。
附有详细注释的完整代码如下:
// 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;https://stackoverflow.com/questions/63608870
复制相似问题