Categories: Development

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.

 

Share
Tags: PHPWeb Dev

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago