How to Check if a String Contains a Substring in PHP
To check if a string contains a substring in PHP, you can use several functions depending on your needs. Here are the most commonly used methods:
1. strpos()
Function
The strpos()
function is commonly used to find the position of the first occurrence of a substring in a string. If the substring is found, it returns the position (index) of the first occurrence. If it’s not found, it returns false
.
$string = "Hello, world!";
$substring = "world";
if (strpos($string, $substring) !== false) {
echo "The substring '$substring' was found in the string.";
} else {
echo "The substring '$substring' was not found in the string.";
}
Note: Use !== false
to check if the result is exactly false
, as strpos()
can return 0
when the substring is found at the beginning of the string.
2. str_contains()
Function (PHP 8.0+)
Starting from PHP 8.0, you can use the str_contains()
function, which simplifies the check and improves readability. It returns true
if the substring is found, otherwise false
.
$string = "Hello, world!";
$substring = "world";
if (str_contains($string, $substring)) {
echo "The substring '$substring' was found in the string.";
} else {
echo "The substring '$substring' was not found in the string.";
}
3. preg_match()
Function
You can also use regular expressions with preg_match()
. This is useful if you need to perform more complex pattern matching.
$string = "Hello, world!";
$substring = "world";
if (preg_match("/" . preg_quote($substring, '/') . "/", $string)) {
echo "The substring '$substring' was found in the string.";
} else {
echo "The substring '$substring' was not found in the string.";
}
Note: preg_quote()
is used to escape any special characters in the substring that might be interpreted as part of the regular expression.
Summary
strpos()
: Use this for compatibility with PHP versions prior to 8.0. Be careful with0
index positions.str_contains()
: Use this for cleaner and more readable code in PHP 8.0 and later.preg_match()
: Use this for more complex matching scenarios involving regular expressions.
Choose the method that best fits your needs based on PHP version and complexity of the substring search.