PHP: str_contains
The str_contains function is used to check if a string contains a given substring; learn how to use it in this tutorial.
By. Jacob
Edited: 2020-07-26 17:49
The str_contains function is used to check if a string contains a given substring; the function is available in PHP 8+ and can replace other, traditional, approaches.
It is not strictly necessary to use this function, as other functions provide the same functionality. Unless you find one is faster than the other, there is indeed little reason to re-write existing code.
str_contains is, however, more readable than using strpos.
The str_contains function may be used like so:
if (str_contains('haystack', 'hay')) {
echo 'Found "hay" in the stack :D';
}
Traditional approaches
The strpos function can also be used for this purpose:
if (false !== strpos('haystack', 'hay')) {
echo 'Found "hay" in the stack :D';
}
Since the function only returns false on failure, we need to check that the function did not return false; if the string is found, a numeric position will be returned, which can also be 0, and since "0" also evaluates to false, we specifically check that: false !== strpos('haystack', 'hay').
Using regular expressions is also possible, and enables us to define where in the string the engine should look for the substring; but this is not needed for a simple substring search.
Links
- PHP RFC: str_contains - php.net
Tell us what you think: