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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3