startsWith() and endsWith() functions in PHP

PHP 8.0 and higher

Since PHP 8.0 you can use the

str_starts_with
Manual
and

str_ends_with Manual

Example

echo str_starts_with($str, '|');

PHP before 8.0

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;
}

Leave a Comment