0

I need to only output true if the sentence contain a specific word.

I know I can use the code below to check if a string contains a word and it will output true.

$a = 'How are you?';    

if (strpos($a,'are') !== false) {
echo 'true';
}
else{
echo 'false';

But how would I get it to output false if $a was "Why do you care?"

Renots
  • 15
  • 5

1 Answers1

3

Use a regex with \b anchors for word boundaries:

if(preg_match('/\bare\b/i', $sentence)) {
    echo 'true';
} else {
    echo 'false';
}

the i modifier is for case-insensitivity.

lafor
  • 12,472
  • 4
  • 32
  • 35