How can I write two functions that would take a string and return if it starts with the specified character/string or ends with it?
For example:
$str = '|apples}'; echo startsWith($str, '|'); //Returns true echo endsWith($str, '}'); //Returns true
STARTSWITH is a string manipulation function that manipulates all string data types (BIT, BLOB, and CHARACTER), and returns a Boolean value to indicate whether one string begins with another.
To check if string ends with specific substring, use strcmp() function to compare the given substring and the string from a specific position of the string. Take string in variable $string. Take substring in $substring. Compute the length of $substring and store it in $length.
Just use substr( $string, 0, strlen($query) ) === $query. Per the str_starts_with RFC, the most CPU and memory efficient way to generically check if a string starts with another string prior to PHP 8 is strncmp($haystack, $needle, strlen($needle)) === 0 .
Returns: A boolean value: true - if the string starts with the specified character(s) false - if the string does not start with the specified character(s)
Since PHP 8.0 you can use the
str_starts_with
Manual and
str_ends_with
Manual
echo str_starts_with($str, '|');
function startsWith( $haystack, $needle ) { $length = strlen( $needle ); return substr( $haystack, 0, $length ) === $needle; }
function endsWith( $haystack, $needle ) { $length = strlen( $needle ); if( !$length ) { return true; } return substr( $haystack, -$length ) === $needle; }
You can use substr_compare
function to check start-with and ends-with:
function startsWith($haystack, $needle) { return substr_compare($haystack, $needle, 0, strlen($needle)) === 0; } function endsWith($haystack, $needle) { return substr_compare($haystack, $needle, -strlen($needle)) === 0; }
This should be one of the fastest solutions on PHP 7 (benchmark script). Tested against 8KB haystacks, various length needles and full, partial and no match cases. strncmp
is a touch faster for starts-with but it cannot check ends-with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With