Home >Backend Development >PHP Tutorial >How Do PHP's `startsWith()` and `endsWith()` Functions Work, and What Are Their Built-in Equivalents?
To check whether a given string begins or concludes with a particular character or substring, you can implement two functions: startsWith() and endsWith().
startsWith()
function startsWith($haystack, $needle) { $length = strlen($needle); return substr($haystack, 0, $length) === $needle; }
This function checks if the initial portion of the haystack matches the specified needle. If they do, it returns true; otherwise, it returns false.
endsWith()
function endsWith($haystack, $needle) { $length = strlen($needle); if (!$length) { return true; } return substr($haystack, -$length) === $needle; }
The endsWith() function works similarly, but it examines the end of the haystack for the presence of the needle.
Consider the following code snippet:
$str = '|apples}'; echo startsWith($str, '|'); // Returns true echo endsWith($str, '}'); // Returns true
In this example, the startsWith() function checks if the string begins with the pipe character '|', and it returns true because the string indeed starts with that character. Similarly, the endsWith() function verifies that the string ends with the '}' curly brace, also returning true.
In PHP 8.0 and later versions, the str_starts_with() and str_ends_with() functions provide a built-in solution for these tasks. They offer improved performance and ease of use compared to custom implementations.
The above is the detailed content of How Do PHP's `startsWith()` and `endsWith()` Functions Work, and What Are Their Built-in Equivalents?. For more information, please follow other related articles on the PHP Chinese website!