Hello Friends Today, through this tutorial, I will tell you How do you check if a string ends with a specific substring in PHP With Example? In PHP, you can check if a string ends with a specific substring using the `substr()` function along with comparison or by using the `substr_compare()` function. Additionally, PHP 8 introduced a dedicated function `str_ends_with()` for this purpose. Here’s how you can achieve it using each method:
1. Using `substr()` and comparison:
<?php $string = "This is a sample string"; $substring = "string"; if (substr($string, -strlen($substring)) === $substring) { echo "The string ends with '$substring'."; } else { echo "The string does not end with '$substring'."; } ?>
2. Using `substr_compare()`:
<?php $string = "This is a sample string"; $substring = "string"; if (substr_compare($string, $substring, -strlen($substring)) === 0) { echo "The string ends with '$substring'."; } else { echo "The string does not end with '$substring'."; } ?>
3. Using `str_ends_with()` (PHP 8 and later):
<?php $string = "This is a sample string"; $substring = "string"; if (str_ends_with($string, $substring)) { echo "The string ends with '$substring'."; } else { echo "The string does not end with '$substring'."; } ?>
These methods will output:
The string ends with 'string'.
Each of these methods achieves the same result, but using `str_ends_with()` is more concise and clearer in indicating the intention of checking if a string ends with a specific substring.