How To Check If a String Ends With a Substring in PHP

In PHP, checking if a string ends with a specific substring is a common task that is used in various applications and websites. This can be useful for verifying user input, validating file names, or filtering data. In this article, we will show you how to check if a string ends with a specific substring in PHP.

To check if a string ends with a specific substring in PHP, you can use the substr() and strlen() functions. The substr() function is used to extract a part of a string, and the strlen() function is used to get the length of a string. To check if a string ends with a specific substring, you can use the substr() function to extract the last few characters of the string, and then compare it with the substring using the strlen() function.

For example, if you want to check if the string “hello world” ends with the substring “world”, you can use the following code:

$string = "hello world";
$substring = "world";

if (substr($string, -strlen($substring)) === $substring) {
    echo "The string ends with the substring.";
} else {
    echo "The string does not end with the substring.";
}

In the code above, we have used the substr() function to extract the last few characters of the string, using the length of the substring as the starting position. Then, we have compared the extracted substring with the original substring using the === operator, which checks for both value and type equality.

If the extracted substring matches the original substring, the code will print “The string ends with the substring.” Otherwise, it will print “The string does not end with the substring.”

In conclusion, checking if a string ends with a specific substring in PHP is a simple and useful task that can be used in various applications and websites. By using the substr() and strlen() functions, you can easily check if a string ends with a specific substring and take appropriate actions based on the result. This can help you to verify user input, validate data, and filter information in your PHP scripts.

In: