php 检查字符串是否包含数组中的单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13795789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if string contains word in array
提问by user1879926
This is for a chat page. I have a $string = "This dude is a mothertrucker". I have an array of badwords: $bads = array('truck', 'shot', etc). How could I check to see if $stringcontains any of the words in $bad?
So far I have:
这是一个聊天页面。我有一个$string = "This dude is a mothertrucker". 我有一堆坏词:$bads = array('truck', 'shot', etc). 我如何检查是否$string包含 中的任何单词$bad?
到目前为止,我有:
foreach ($bads as $bad) {
if (strpos($string,$bad) !== false) {
//say NO!
}
else {
// YES! }
}
Except when I do this, when a user types in a word in the $badslist, the output is NO! followed by YES! so for some reason the code is running it twice through.
除非我这样做,当用户在$bads列表中输入一个单词时,输出为 NO!其次是是!所以出于某种原因,代码运行了两次。
采纳答案by Pedro JR
Without wasting time and using these old and long solutions, your best shot should be this:
不浪费时间并使用这些古老而漫长的解决方案,你最好的镜头应该是这样的:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const check = fruits.includes("Mango")
console.log(check) //it should return true
Don't forget to up vote if that works for you
如果这对您有用,请不要忘记投票
回答by Nirav Ranpara
function contains($str, array $arr)
{
foreach($arr as $a) {
if (stripos($str,$a) !== false) return true;
}
return false;
}
回答by T.Todua
1) The simplest way:
1)最简单的方法:
if ( in_array( 'eleven', array('four', 'eleven', 'six') ))
...
2) Another way(while checking arrays towards another arrays):
2)另一种方式(同时检查另一个数组的数组):
$keywords=array('one','two','three');
$targets=array('eleven','six','two');
foreach ( $targets as $string )
{
foreach ( $keywords as $keyword )
{
if ( strpos( $string, $keyword ) !== FALSE )
{ echo "The word appeared !!" }
}
}
回答by Sanjay
can you please try this instead of your code
你能试试这个而不是你的代码吗
$string = "This dude is a mothertrucker";
$bads = array('truck', 'shot');
foreach($bads as $bad) {
$place = strpos($string, $bad);
if (!empty($place)) {
echo 'Bad word';
exit;
} else {
echo "Good";
}
}
回答by Abhijit Amin
You can flip your bad word array and do the same checking much faster. Define each bad word as a key of the array. For example,
您可以翻转坏词数组并更快地进行相同的检查。将每个坏词定义为数组的键。例如,
//define global variable that is available to too part of php script
//you don't want to redefine the array each time you call the function
//as a work around you may write a class if you don't want global variable
$GLOBALS['bad_words']= array('truck' => true, 'shot' => true);
function containsBadWord($str){
//get rid of extra white spaces at the end and beginning of the string
$str= trim($str);
//replace multiple white spaces next to each other with single space.
//So we don't have problem when we use explode on the string(we dont want empty elements in the array)
$str= preg_replace('/\s+/', ' ', $str);
$word_list= explode(" ", $str);
foreach($word_list as $word){
if( isset($GLOBALS['bad_words'][$word]) ){
return true;
}
}
return false;
}
$string = "This dude is a mothertrucker";
if ( !containsBadWord($string) ){
//doesn't contain bad word
}
else{
//contains bad word
}
In this code we are just checking if an index exist rather than comparing bad word with all the words in the bad word list.
isset is much faster than in_array and marginally faster than array_key_exists.
Make sure none of the values in bad word array are set to null.
isset will return false if the array index is set to null.
在这段代码中,我们只是检查索引是否存在,而不是将坏词与坏词列表中的所有词进行比较。
isset 比 in_array 快得多,比 array_key_exists 快一点。
确保坏词数组中的任何值都没有设置为空。
如果数组索引设置为 null,isset 将返回 false。
回答by Sanjay
Put and exit or die once it find any bad words, like this
一旦发现任何不好的词,就放入并退出或死亡,就像这样
foreach ($bads as $bad) {
if (strpos($string,$bad) !== false) {
//say NO!
}
else {
echo YES;
die(); or exit;
}
}
回答by Lenin
Wanted this?
想要这个?
$string = "This dude is a mothertrucker";
$bads = array('truck', 'shot', 'mothertrucker');
foreach ($bads as $bad) {
if (strstr($string,$bad) !== false) {
echo 'NO<br>';
}
else {
echo 'YES<br>';
}
}
回答by Clinton
There is a very short php script that you can use to identify bad words in a string which uses str_ireplace as follows:
有一个非常短的 php 脚本,您可以使用它来识别使用 str_ireplace 的字符串中的坏词,如下所示:
$string = "This dude is a mean mothertrucker";
$badwords = array('truck', 'shot', 'ass');
$banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false;
if ($banstring) {
echo 'Bad words found';
} else {
echo 'No bad words in the string';
}
The single line:
单行:
$banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false;
does all the work.
做所有的工作。
回答by eldhose
You can do the filter this way also
您也可以通过这种方式进行过滤
$string = "This dude is a mothertrucker";
if (preg_match_all('#\b(truck|shot|etc)\b#', $string )) //add all bad words here.
{
echo "There is a bad word in the string";
}
else {
echo "There is no bad word in the string";
}
回答by Irshad Khan
If you want to do with array_intersect(), then use below code :
如果要使用 array_intersect(),请使用以下代码:
function checkString(array $arr, $str) {
$str = preg_replace( array('/[^ \w]+/', '/\s+/'), ' ', strtolower($str) ); // Remove Special Characters and extra spaces -or- convert to LowerCase
$matchedString = array_intersect( explode(' ', $str), $arr);
if ( count($matchedString) > 0 ) {
return true;
}
return false;
}

