Cover Image for PHP STR_CONTAINS()
153 views

PHP STR_CONTAINS()

As of my last update in September 2021, there is no built-in str_contains() function in PHP. However, PHP provides other functions that can be used to check if a string contains a specific substring. Some of these functions are:

  1. strpos(): The strpos() function is used to find the position of the first occurrence of a substring in a string. It returns the position as an integer, or false if the substring is not found.
$string = "Hello, world!";
$substring = "world";

if (strpos($string, $substring) !== false) {
    echo "Substring found in the string.";
} else {
    echo "Substring not found in the string.";
}
  1. stripos(): The stripos() function is similar to strpos(), but it performs a case-insensitive search.
$string = "Hello, World!";
$substring = "world";

if (stripos($string, $substring) !== false) {
    echo "Substring found in the string (case-insensitive).";
} else {
    echo "Substring not found in the string.";
}
  1. strstr(): The strstr() function is used to find the first occurrence of a substring in a string and return the rest of the string from that position. It returns false if the substring is not found.
$string = "Hello, world!";
$substring = "world";

$result = strstr($string, $substring);

if ($result !== false) {
    echo "Substring found in the string: " . $result;
} else {
    echo "Substring not found in the string.";
}
  1. stristr(): The stristr() function is similar to strstr(), but it performs a case-insensitive search.
$string = "Hello, World!";
$substring = "world";

$result = stristr($string, $substring);

if ($result !== false) {
    echo "Substring found in the string (case-insensitive): " . $result;
} else {
    echo "Substring not found in the string.";
}

Keep in mind that the availability of functions may change in newer PHP versions, so always refer to the PHP manual for the specific version you are using. As of my last update, the above functions are available in PHP and can be used to check if a string contains a specific substring.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS