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:
'Hello World', 'Hello');str_contains(
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.
'Hello World', 'Hello') !== false;strpos(
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 is case-sensitive so the capitalization must match. There is also a
stripos function that is case insensitive so capitalization doesn’t matter.
'Hello World', 'hello') !== false;stripos(
If you found this article useful, consider following me on Twitter so you don't miss out on more PHP Pro Tips!