Home >Backend Development >PHP Tutorial >PHP how to check if a string ends with a given substring

PHP how to check if a string ends with a given substring

PHPz
PHPzforward
2024-03-19 12:43:061037browse

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:

  • endsWith(): This function is specially used to check whether the string ends with the given substring. It returns a Boolean value indicating whether the string ends with this substring. For example:
$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.";
}
  • substr_compare(): This function can be used to compare part of a string with another string. To check if a string ends with a substring you can use the following syntax:
$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.";
}
  • preg_match(): Using regular expressions is also a way to check if a string ends with a given substring. For example:
$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!

Statement:
This article is reproduced at:lsjlt.com. If there is any infringement, please contact admin@php.cn delete