Avatar
7979 reputation
Posted on:23 Aug '16 - 10:37
5

startsWith() and endsWith() 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

C#

Answers

50
This answer is accepted

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);
}
Use this if you don't want to use a regex.

Avatar
7718 reputation
Posted on:24 Aug '16 - 04:37

Please login in order to answer a question