Join my Laravel for REST API's course on Udemy 👀

Check if string contains substring in PHP

March 14, 2021  ‐ 1 min read

In order to check if a string contains a word, letter (any kind of substring) you use the strpos() function. Which looks for the first occurrence of the substring in the string you want to search. It returns the position of the first occurrence in the string and false if the substring couldn't be found.

<?php

if(strpos('Graphpaper', 'php') !== false)
{
    echo 'Word contains "php"';
}
else
{
    echo 'Word does not contains "php"';
}

# => Word contains "php"

Since PHP 8 you have some new sugar to check for substrings, the str_contains() which was introduced in PHP 8.

<?php

if(str_contains('Graphpaper', 'php'))
{
    echo 'Word contains "php"';
}
else
{
    echo 'Word does not contains "php"';
}

# => Word contains "php"