Home > Article > Backend Development > PHP how to check if a string ends with a given substring
php editor Youzi will introduce you in detail how to use PHP to check whether a string ends with a specified substring. In PHP, you can use the built-in functions substr() and strlen() to achieve this functionality. By comparing the substring at the end of the original string with the given substring, you can determine whether the string ends with the specified substring. Below are specific code examples and explanations to help you implement this functionality easily.
PHP method to check if a string ends with a given substring
In php, there are multiple ways to check if a string ends with a given substring. The most common way is to use the following functions:
$string = "This is a test string."; $substring = "test string"; if (endsWith($string, $substring)) { echo "The string ends with the given substring."; } else { echo "The string does not end with the given substring."; }
$string = "This is a test string."; $substring = "test string"; $result = substr_compare($string, $substring, -strlen($substring)); if ($result == 0) { echo "The string ends with the given substring."; } else { echo "The string does not end with the given substring."; }
$string = "This is a test string."; $substring = "test string"; $pattern = "/$substring$/"; if (preg_match($pattern, $string)) { echo "The string ends with the given substring."; } else { echo "The string does not end with the given substring."; }
All the above methods can effectively check whether a string ends with a given substring in PHP. Which method you choose depends on your specific needs and the performance requirements of your application.
The above is the detailed content of PHP how to check if a string ends with a given substring. For more information, please follow other related articles on the PHP Chinese website!