If we want to check a specific word contains in another string. It’s common this kind of requirement while developing projects in PHP.
We can use strpos function which is used to find the occurrence of one string inside another:
$str = 'How are you buddy?'; if (strpos($str, 'are') !== false) { echo 'true'; }
You notice that I used the check against the false as strpos
returns the string occurrence number in another string. Since 0 is a number we can’t use like this !(strpos($str, 'are')
this will give the wrong result.
We have another method to do this elegantly, by using the regular expression. Yes, we can check if a string contains a specific word in PHP using regular expression.
A simple match for are
could look something like this:
$a = 'How are you buddy?'; if (preg_match('/\bare\b/', $a)) { echo 'true'; }
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply