How to Check if a String Ends with Another String in PHP?

Problem:

You have a string. You want to check if that string ends with another string or a character.

Solution:

PHP has a built-in funcation named substr_compare() which is used to compare two strings. We’ll use this function to compare if a string or a character ends with another string. See the example below-

[php]
<?php
$string = "Learn web development from SchoolsofWeb.com";
$subString = "SchoolsofWeb.com";
$result = substr_compare($string, $subString, -16, 16);
echo ($result === 0)? "Yes, the string \"$string\" ends with \"$subString\" ": "No, the string \"$string\" doesn’t end with \"$subString\"";
?>
[/php]

[wpdm_file id=121]

Output:
Y
es, the string “Learn web development from SchoolsofWeb.com” ends with “SchoolsofWeb.com”.

How it works:

Line 2 The main string
Line 3 The substring to be compared with. It has 16 characters.
Line 4 The substr_compare() function finds if $subString(second parameter) starts from the last 16 characters(the negative sign in the third parameters asks to compare from the end) of the $string string(first parameter) and ends after 16 character(fourth parameter which is the length of the $subString). If the function finds the matches, it returns 0 and we store it in $return variable.
Line 5 If the $return variable is equal to 0, then we print the first success message, else the next one.

One Reply to “How to Check if a String Ends with Another String in PHP?”

  1. Nice post. I was looking to see if PHP had some sort of an ends_with function, but this works just as well, since it can be done in a single line. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *