0

I want to find the whole words in text not a sub string. I have written following code.

$str = 'its so old now.';
$a   = 'so';
if (stripos($str,$a) !== false) {
 echo 'true';
} else {
 echo 'false';
}

str1 = 'its so old now.';
str2 = 'it has some issue.';

I want to find word 'so' in text. it give true in both the string. But I want true in first case only because in second string 'so' contains in 'some' words.

Thanks in advance

Mohan Kute
  • 137
  • 1
  • 3
  • 14
  • 1
    Possible duplicate of [Check if string contains specific words?](http://stackoverflow.com/questions/4366730/check-if-string-contains-specific-words) – l'L'l Jun 13 '16 at 09:45

1 Answers1

6

\b can be used in regex to match word boundaries.

\bso\b

Should only match so when it is on it's own:

if(preg_match('/\bso\b/',$str)){
    echo "Matches!";
}

Note that preg_match returns 0 on no match and false on error so you may wish to check for these values. The above is also case insensitive. You can use /\bso\b/i to ignore case.

Jim
  • 22,354
  • 6
  • 52
  • 80
  • It's no working when I need to detect 'true' word in the haystack string. That means when the haystack is equal to 'true' or 'some text' it returns true in both! – Babaktrad Dec 21 '21 at 06:49
  • @Babaktrad I think you have a mistake in your code. It does work for true: https://3v4l.org/DDmKV – Jim Jan 05 '22 at 10:14