In PHP 8.0 a handy new function was added that allows you to determine if one string contains another substring. This is the str_contains function.
It is used like this:
<?php
str_contains('Hello World', 'Hello');
Returns true. If the string is not found, this returns false. Nice and simple!
If you’re using an older version of PHP, you may want to do something like this.
<?php
strpos('Hello World', 'Hello') !== false;
strpos
returns the position in which the substring exists in the string (the very beginning being position 0, so a 0 return also means that the substring was found). This is less direct and readable than the new str_contains function but will work on much older versions of PHP.
What is the difference between strpos
vs stripos
?
strpos
is case-sensitive so the capitalization must match. There is also a stripos
function that is case insensitive so capitalization doesn’t matter.
<?php
stripos('Hello World', 'hello') !== false;
If you found this article useful, consider following me on Twitter so you don't miss out on more PHP Pro Tips!