Ayo Ojosipe
Ayo Ojosipe

Reputation: 49

Using PHP stripos() in Logical Filtering

How can i use the stripos to filter out unwanted word existing on itself. How do i twist the code below that a search for 'won' in grammar will not return true, since 'wonderful' is another word itself.

$grammar = 'it is a wonderful day';
$bad_word = 'won';

$res = stripos($grammar, $bad_word,0);

if($res === true){
       echo 'bad word present';
}else{
       echo 'no bad word'; 
}

//result  'bad word present'

Upvotes: 1

Views: 48

Answers (2)

Ayo Ojosipe
Ayo Ojosipe

Reputation: 49

 $grammar = 'it is a wonderful day';
 $bad_word = 'won';

        /*  \b   \b indicates a word boundary, so only the distinct won not wonderful is  searched   */

 if(preg_match("/\bwon\b/i","it is a wonderful day")){ 
    echo "bad word was found";} 
 else { 
    echo "bad word not found"; 
    } 

//result is : bad word not found 

Upvotes: 1

Ole Spaarmann
Ole Spaarmann

Reputation: 16751

Use preg_match

$grammar = 'it is a wonderful day';
$bad_word = 'won';
$pattern = "/ +" . $bad_word . " +/i"; 

// works with one ore more spaces around the bad word, /i means it's not case sensitive

$res = preg_match($pattern, $grammar);
// returns 1 if the pattern has been found

if($res == 1){
  echo 'bad word present';
}
else{
  echo 'no bad word'; 
}

Upvotes: 1

Related Questions