Check if string contains word in array

后端 未结 12 1334
旧巷少年郎
旧巷少年郎 2020-12-01 09:12

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)

相关标签:
12条回答
  • 2020-12-01 09:51

    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;
    }
    
    0 讨论(0)
  • 2020-12-01 09:53

    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)

    0 讨论(0)
  • 2020-12-01 09:55

    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 !!" }
      }
    }
    
    0 讨论(0)
  • 2020-12-01 09:58
    function contains($str, array $arr)
    {
        foreach($arr as $a) {
            if (stripos($str,$a) !== false) return true;
        }
        return false;
    }
    
    0 讨论(0)
  • 2020-12-01 10:03

    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>';
            }
        }
    
    0 讨论(0)
  • 2020-12-01 10:05

    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";
       }
    
    0 讨论(0)
提交回复
热议问题