Recent Posts

Start with and end with string function on PHP


This two functions take a string a verify if it starts with a specified character/string or ends with it

For example:

$str = '|apples}';

echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true
Functions code:

function startsWith($haystack, $needle)
{
    return $needle === "" || strpos($haystack, $needle) === 0;
}
function endsWith($haystack, $needle)
{
    return $needle === "" || substr($haystack, -strlen($needle)) === $needle;
}

var_dump(startsWith("hello world", "hello")); // true
var_dump(endsWith("hello world", "world"));   // true
Java and .NET implementations of String.StartsWith and String.EndsWith return true if needle is an empty string. Answer revised accordingly.

This another function is faster for large haystack:

function startsWith($haystack, $needle)
{
     $length = strlen($needle);
     return (substr($haystack, 0, $length) === $needle);
}

function endsWith($haystack, $needle)
{
    $length = strlen($needle);
    if ($length == 0) {
        return true;
    }

    return (substr($haystack, -$length) === $needle);
}



No comments:

Post a Comment