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.

2042 views
d

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

  1. PHP RFC: str_contains - php.net

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials