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:
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.
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.
Write comment about this article: