PHP str_ends_with() - Check String Ending
The str_ends_with() function in PHP provides a simple and efficient way to check if a string ends with a specific substring. Whether you are verifying file extensions, URL endings, or just want to know if a string has a particular suffix, this function makes the task straightforward and clean.
Introduction
When working with strings in PHP, it is common to need to check whether a given string ends with a particular sequence of characters (a suffix). Before PHP 8.0, developers had to rely on functions like substr() or strrpos() to perform this operation.
The str_ends_with() function, introduced in PHP 8.0, simplifies this task by returning a boolean indicating whether the specified haystack string ends with the needle substring.
Prerequisites
- Basic knowledge of PHP syntax and string manipulation.
- PHP 8.0 or later installed on your environment (because
str_ends_with()is available starting PHP 8.0).
Setup
To use str_ends_with(), ensure your PHP version is 8.0 or above. You can verify this by running:
php -v
If you need to update PHP, follow your system or hosting providerβs instructions.
Function Syntax
bool str_ends_with(string $haystack, string $needle)
$haystack: The input string to search in.$needle: The substring to look for at the end of$haystack.- Returns
trueif$haystackends with$needle, otherwisefalse.
Examples Explained
Example 1: Basic Usage
<?php
$string = "hello_world.php";
if (str_ends_with($string, ".php")) {
echo "The string ends with .php";
} else {
echo "The string does not end with .php";
}
?>
Output: The string ends with .php
This example checks if the filename stored in $string has the .php extension.
Example 2: Checking URL Endings
<?php
$url = "https://example.com/about-us/";
if (str_ends_with($url, "/")) {
echo "URL ends with a slash.";
} else {
echo "URL does not end with a slash.";
}
?>
Output: URL ends with a slash.
This example can be useful if you need to normalize URLs or ensure that they end with a slash for consistency.
Example 3: When Needle is Empty String
<?php
$text = "OpenAI GPT";
var_dump(str_ends_with($text, "")); // bool(true)
?>
An empty string as the needle always returns true, since every string ends with an empty substring.
Example 4: Case-Sensitive Check
<?php
$filename = "Report.PDF";
var_dump(str_ends_with($filename, ".pdf")); // bool(false)
var_dump(str_ends_with($filename, ".PDF")); // bool(true)
?>
Note that str_ends_with() is case-sensitive. ".pdf" does not match ".PDF". Use strtolower() to perform case-insensitive checks.
Example 5: Case-Insensitive Suffix Check (Workaround)
<?php
$filename = "Report.PDF";
$suffix = ".pdf";
if (str_ends_with(strtolower($filename), strtolower($suffix))) {
echo "Filename ends with .pdf (case-insensitive check)";
} else {
echo "Filename does not end with .pdf";
}
?>
Best Practices
- Always verify PHP version: Since
str_ends_with()requires PHP 8.0+, check your environment compatibility. - Case sensitivity: Remember the function is case-sensitive. Normalize strings with
strtolower()orstrtoupper()if case-insensitive checks are needed. - Empty needle handling: An empty needle always returns
true. Handle this as a special case if necessary. - Use for validation: Commonly use this function to verify file extensions, URL formats, or input suffixes.
- Alternative for older PHP: For PHP versions below 8.0, use
substr_compare()or custom helper functions.
Common Mistakes
- Using the function in PHP versions lower than 8.0 (results in undefined function error).
- Expecting the function to be case-insensitive by default.
- Passing non-string parameters (always ensure both haystack and needle are strings).
- Incorrectly handling empty needles or null inputs.
- Confusing
str_ends_with()withstrpos()orsubstr(), which handle different tasks.
Interview Questions
Junior-Level Questions
-
Q1: What does the
str_ends_with()function do in PHP?
A1: It checks if a given string ends with a specified substring and returns true or false. -
Q2: Since which PHP version is
str_ends_with()available?
A2: It is available from PHP 8.0 onwards. -
Q3: Is
str_ends_with()case-sensitive?
A3: Yes, it performs a case-sensitive check by default. -
Q4: What does
str_ends_with("hello", "")return?
A4: It returns true because every string ends with an empty substring. -
Q5: How do you check if a string ends with ".php" using
str_ends_with()?
A5: Usestr_ends_with($string, ".php").
Mid-Level Questions
-
Q1: How would you perform a case-insensitive suffix check using
str_ends_with()?
A1: Convert both strings to lowercase usingstrtolower()before callingstr_ends_with(). -
Q2: What is the return type of
str_ends_with()?
A2: It returns a boolean:trueif the haystack ends with the needle, otherwisefalse. -
Q3: What will happen if the needle is longer than the haystack?
A3: The function returnsfalsebecause the haystack cannot end with a longer string. -
Q4: Can
str_ends_with()be used to validate file extensions? Why?
A4: Yes, because file extensions are suffixes of file names, andstr_ends_with()can check those suffixes easily. -
Q5: Is
str_ends_with()faster than usingsubstr()for suffix verification?
A5: Generally, yes β itβs optimized internally and provides clearer, more readable code.
Senior-Level Questions
-
Q1: How does
str_ends_with()behave internally when checking for the needle substring?
A1: Internally, it compares the last portion of the haystack matching the needleβs length, returning true if they are identical. -
Q2: How would you handle suffix checking for multibyte (UTF-8) strings using
str_ends_with()?
A2: Sincestr_ends_with()works on bytes, ensure input strings are UTF-8 encoded and use it cautiously or consider multibyte-safe functions if needed. -
Q3: What are potential security implications of incorrectly checking file extensions with
str_ends_with()?
A3: Attackers may bypass checks by crafting filenames with malicious content and misleading extensions; always validate content type, not just extension. -
Q4: Can you create a polyfill for
str_ends_with()for PHP < 8.0? Show an example.
A4: Yes. For example:if (!function_exists('str_ends_with')) { function str_ends_with(string $haystack, string $needle): bool { $needleLen = strlen($needle); if ($needleLen === 0) { return true; } return substr($haystack, -$needleLen) === $needle; } } -
Q5: How would you optimize multiple suffix checks on the same string using
str_ends_with()?
A5: Loop through an array of suffixes and callstr_ends_with()once for each. For large sets, consider building a trie or use regex for batch suffix checks.
Frequently Asked Questions (FAQ)
Q1: What happens if the needle is an empty string?
When needle is empty, str_ends_with() returns true by definition, since every string ends with an empty substring.
Q2: Is there a case-insensitive version of str_ends_with() in PHP?
No, PHP does not provide a case-insensitive version of this function. You can convert both strings to lowercase (or uppercase) before using str_ends_with() to simulate case-insensitive behavior.
Q3: Can str_ends_with() be used with non-ASCII characters?
Yes, but be aware that PHP string functions operate at byte level. If you work with multibyte encodings like UTF-8, ensure the input strings are properly encoded and the suffix matches byte sequences accurately.
Q4: How does str_ends_with() differ from substr()?
str_ends_with() is a boolean check specifically designed to test suffixes and returns true or false. substr() extracts part of a string, and you would need extra comparison logic to check suffixes manually.
Q5: What should I do if my PHP version is below 8.0 but I want to use str_ends_with()?
You can create a polyfill function using substr() and strlen(), or update your PHP version to 8.0 or higher to use the native implementation.
Conclusion
The str_ends_with() function in PHP 8.0+ offers a concise and efficient way to verify if a string concludes with a certain substring. It improves code readability and reduces complexity compared to older approaches.
Whether you are validating file extensions, URL paths, or other suffixes, understanding and implementing str_ends_with() correctly can streamline your PHP string processing tasks.
Always consider the PHP version compatibility and case sensitivity when working with this function to avoid common pitfalls.