How to check if a string exists in PHP
You can use the strpos() function in PHP to check if a string exists.
The strpos() function is used to locate the first occurrence of a substring within a string. It returns the index position of the substring within the original string if found, and false if not found.
Here is an example of checking if a string exists using the strpos() function:
$string = "Hello, world!";
$substring = "world";
if (strpos($string, $substring) !== false) {
echo "Substring found!";
} else {
echo "Substring not found!";
}
In the example above, “Hello, world!” is the main string to be searched, while “world” is the substring to look for. If the substring is found within the original string, it will output “Substring found!”. If the substring is not found, it will output “Substring not found!”.
Please note that the return value of the strpos() function is an integer (the position index of the substring) or false (if the substring is not found). Therefore, it is necessary to use the not identical (!==) operator to compare, in order to correctly handle both integer and false return values.