• support@answerspoint.com

startsWith() and endsWith() functions in PHP

903

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
  • PHP

  • asked 3 years ago
  • B Butts

2Answer


0
<?php
function startsWith($haystack, $needle)
{
    return strncmp($haystack, $needle, strlen($needle)) === 0;
}

function endsWith($haystack, $needle)
{
    return $needle === '' || substr_compare($haystack, $needle, -strlen($needle)) === 0;
}
  • answered 3 years ago
  • Gul Hafiz

0

It is possible to use strrpos and strpos to check start-with and ends-with respectively:

function startsWith($haystack, $needle) {
    // search backwards starting from haystack length characters from the end
    return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== false;
}

function endsWith($haystack, $needle) {
    // search forward starting from end minus needle length characters
    return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}

Tests and results (compare with this):

startsWith("abcdef", "ab") -> true
startsWith("abcdef", "cd") -> false
startsWith("abcdef", "ef") -> false
startsWith("abcdef", "") -> true
startsWith("", "abcdef") -> false

endsWith("abcdef", "ab") -> false
endsWith("abcdef", "cd") -> false
endsWith("abcdef", "ef") -> true
endsWith("abcdef", "") -> true
endsWith("", "abcdef") -> false

Note: the strncmp and substr_compare functions will outperform this function.

  • answered 3 years ago
  • G John

Your Answer

    Facebook Share        
       
  • asked 3 years ago
  • viewed 903 times
  • active 3 years ago

Hot Questions