PHP 8.0 : str_starts_with() and str_ends_with()
08, May 2020

Even though PHP has many helper functions to deal with strings, They still not cover all the use-cases web development requires. But good thing is, PHP internals are always coming u with their idea to make php developers life easier with string functions. God bless them.


Two of such cases are:

  • To check if $haystack string starts with $needle string.
  • To check if $haystack string ends with $needle string.


str_starts_with()

<?php
$haystack = 'Twinkle Twinkle Little Star';
$needle = 'Twinkle Twin';

var_dump(str_starts_with($haystack, $needle)); 
// true

str_ends_with()

<?php
$haystack = 'Twinkle Twinkle Little Star';
$needle = 'le Star';

var_dump(str_ends_with($haystack, $needle));
// true

Note: empty string as $needle will always return with true. see the reason at str_contains


But, We already can do them in userland.

Yes, we already can achieve the same result using functions like substr, strpos, strncmp, substr_compare But They have their own issues which we need to handle each time using them.

  • Some of them (eg. strpos) are CPU inefficient as they search the whole $haystack string while we only need to check the start/end of it.
  • Some of them(eg. substr) are Memory inefficient as they cut part of string in the process.
  • Most of them are too verbose to know what they are doing in a single glance.
  • They are too error prone. And I say this from experience. Each time I implement any of these functions, I have to be extremely careful as they need extra attention to their return types. Do I need to check === false ??? or === 0 ??? Does this function return boolean or int or string ???


Where are case-insensitive and multi-byte versions?

Currently, we don't have any case-insensitive and multi-byte version of str_starts with() and str_ends_with(). These two function will work with multi-byte strings just fine. But if you need case-insensitive ones, you need to fallback to current userland implementations.