Search code examples
phpstringstrpos

How to check if word exist in a string with php


How can i check if word exist in a string.

I tried strpos but not with good results.

My example if(strpos($string, 'As ') !== false)

And string is :

"Asthmatic is ruff"

Then it gives me true, as the As is included.

But i need to find word

"As" or "as"

Example:

"As i walked" or "If it was as"


Solution

  • if (preg_match('/\b(as)\b/i', $string, $matches)) {
        //$string had the word 'as' in it
    }
    

    Use preg_match to match regular expressions. \b indicates a word boundary. i at the end indicates the match will be case-insensitive