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

PHPz
Release: 2024-03-19 12:46:02
forward
1014 people have browsed it

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.";
}
Copy after login
  • 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.";
}
Copy after login
  • 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.";
}
Copy after login

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!

source:lsjlt.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template