Beamtic's logo
  1. Create user
Home

Share via:

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.

64 views

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

  1. PHP RFC: str_contains - php.net

Comments

  1. How to count the number of characters in a multi-byte string using PHP.
  2. Learn what PHP objects are, and how to use them in your own PHP coding adventures.
  3. Why the caret character is not working in exponential growth calculations in PHP, and what to use instead.
  4. Vanilla PHP is basically plain PHP, without the use of extra frameworks and libraries to help you in the development process.
  5. Tutorial showing how to check if a variable is a number in PHP

More in: PHP Tutorials