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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago