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
Since PHP 8.0 you can use:
str_starts_with
and
str_ends_with
var_dump(str_starts_with('|apples}', '|'));
var_dump(str_ends_with('|apples}', '}'));
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;
}