PHP str_contains() is born

Early 2020 there was this post on /r/PHP posing the question “With so many features added to PHP, why is there no str_contains?”.

flippeeer who submitted this post is right, you can find if a string contains a letter/word/sentence but it isn’t a direct method nor intended use:

if (strpos('This is the string to be searched.', 'searched') !== false) {
    echo 'Yes';//Does contain searched

You have to use strpos() to check if there is no first occurrence of the needle (search term). It does the job but not direct nor fully clean.

From the Reddit post str_contains was formulated and applied in a pull request for the PHP main branch.

The str_contains use will looks like this:

str_contains(string $haystack, string $needle): bool

Returning true on needle being found in haystack and false for it not being found.

if (str_contains('This is the string to be searched', 'searched')){
echo 'Yes';

Now you can easily check if a string contains a word without having to use an unrelated function and check for it not being false.

Because as of the 16th March 2020 str_contains has been added to PHP.

Incredible to think that 25 years of PHP and there hasn’t been a direct string contains function. Yes its easy to make a custom one but having a set in stone, packaged official function is right.