phpstring

str_starts_with and str_ends_with functions in PHP


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

Solution

  • PHP 8.0 and higher

    Since PHP 8.0 you can use:

    str_starts_with and
    str_ends_with

    Example
    var_dump(str_starts_with('|apples}', '|'));
    var_dump(str_ends_with('|apples}', '}'));
    

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