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)
If you want to do with array_intersect(), then use below code :
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;
}
Your best shot should be to run this code on the client side I.e only when JavaScript is available
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const check = fruits.includes("Mango")
// console.log(check)
it returned true because mango is in the array. if mango was not in the array it will return false
not PHP, strictly for JavaScript(client side)
1) The simplest way:
if ( in_array( 'eleven', array('four', 'eleven', 'six') ))
...
2) Another way (while checking arrays towards another arrays):
$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 !!" }
}
}
function contains($str, array $arr)
{
foreach($arr as $a) {
if (stripos($str,$a) !== false) return true;
}
return false;
}
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>';
}
}
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";
}