Search code examples
phpmysqlregexstringsql-like

Find where and which word matched sql LIKE statement


I am using a very long like query to detect offensive words within my users usernames.

I have made a moderator page where the moderator can click a button next to the detected username and it will replace the offending word with *'s. The problem is how can I easily detect which offensive word and where to replace?

I guess I would need to use a regex of some description that functions exactly the same as the LIKE statement. Help in creating such a regex would be greatly appropriated or... if anyone has a better solution.

TIA


Solution

  • Something like:

    $bad_list = array('foo','barr','ax'); // list of bad words you want to *
    
    $from = array();
    $to = array();
    
    foreach($bad_list as $s){
        $from[] = '/'.preg_quote($s,'/').'/'; // PHP expects regex in delimiter.
        $to[] = str_repeat('*',strlen($s));
    }
    $str = "afoob";
    $str = preg_replace($from,$to,$str); // $str is now a***b
    

    You might also use str_replace, there is really no need of regex here.