Check if string contains a substring using PHP
If you're working with strings in PHP, it's often necessary to check if a string contains a particular substring. For instance, you might want to check if a string contains a URL or an email address.
<?php
if (strpos("Hello World", "Wor") != false) {
echo "Substring found";
} else {
echo "Substring not found";
}
?>
Output
Substring found
PHP provides a number of functions that make it easy to check if a string contains a substring. In this article, we'll take a look at a few of these functions and how they can be used to check if a string contains a substring.
Using str_contains() function if you are using PHP 8 or higher version
The str_contains() function is used to check if a string contains a substring. This function is available in PHP 8 or higher version. This function is case-sensitive means it will make an exact match with your string.
<?php
if (str_contains("Hello World", "Wor")) {
echo "Substring found";
} else {
echo "Substring not found";
}
?>
Output
Substring found
Check if string contains a substring using strpos() function
The strpos() function is used to check if a string contains a substring. If the substring is found, the function returns the position of the first character of the substring. If the substring is not found, the function returns false.
Code Example 1
<?php
if (strpos("Every company is a tech company", "tech")) {
echo "Match found";
} else {
echo "Match not found";
}
?>
Output
Match found
Code Example 2
<?php
if (strpos("Every company is a tech company", "technology")) {
echo "Match found";
} else{
echo "Match not found";
}
?>
Output
Match not found
You can use the strpos() function to check if a string contains a specific word or phrase. For example, to check if the string "The quick brown fox" contains the word "fox", you would use the following code:
if (strpos($string, 'fox') !== false) {
echo 'The string contains the word "fox"';
}
else {
echo 'The string does not contain the word "fox"';
}