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


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


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-

$string = "Learn web development from";
$subString = "";
$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\"";

[wpdm_file id=121]

es, the string “Learn web development from” ends with “”.

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.