How to check if a string contains a specific word or substring in PHP?

Check how to find a specific word or substring in PHP 8 or below using str_contains and strpos

by cybersal
5 mins read

Before PHP 8 we can use strpos function of PHP to find a specific word or substring within a string. (substring in PHP)

You can use the strpos() function which is used to find the occurrence of one string inside another one (substring in PHP):

$a = 'Check substring within a string in PHP?';

if (strpos($a, 'substring') !== false) {
    echo 'true';

strpos() returns either the offset at which the needle string begins in the string, or the boolean false if the needle isn’t found.

With PHP 8

PHP 8 offers str_contains function. Function returns boolean.

if (str_contains('How are you', 'are')) { 
    echo 'true';

Related Articles

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Privacy & Cookies Policy