Using PHP str_ends_with() Function: Syntax, Usage, and Case Sensitivity
This article explains PHP's str_ends_with() function, detailing its syntax, parameters, return values, usage examples, case‑sensitivity considerations, and how to combine it with strtolower() for case‑insensitive checks, while also noting its limitation to end‑string matching.
In everyday PHP programming, you may need to determine whether a string ends with a specific character or substring. PHP provides the useful str_ends_with() function for this purpose.
Basic Syntax of str_ends_with()
bool str_ends_with(string $haystack, string $needle)The function accepts two parameters: $haystack, the string to search, and $needle, the substring to match at the end. It returns true if $haystack ends with $needle, otherwise false.
Usage of str_ends_with()
$str1 = "Hello, World!";
$str2 = "This is a test.";
$str3 = "Welcome to PHP.";
var_dump(str_ends_with($str1, "World!")); // bool(true)
var_dump(str_ends_with($str1, "World")); // bool(false)
var_dump(str_ends_with($str2, "test.")); // bool(true)
var_dump(str_ends_with($str3, "PHP.")); // bool(false)These examples show that str_ends_with() accurately determines whether a string ends with the specified substring and returns the corresponding boolean value.
Note that str_ends_with() is case‑sensitive. If the case does not match, the function returns false. To perform a case‑insensitive check, you can convert both strings to lower case using strtolower() before comparison.
Example Using strtolower()
$str = "Hello, World!";
$end = "world!";
var_dump(str_ends_with(strtolower($str), strtolower($end))); // bool(true)Besides case sensitivity, str_ends_with() can only check the end of a string; it cannot check the beginning or middle. For those cases, functions like str_starts_with() and strstr() should be used.
Overall, str_ends_with() is a practical PHP function for quickly and accurately checking string endings, provided you are aware of its case‑sensitivity and its limitation to end‑position checks.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
