Monday, June 10, 2019

string - 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

Answer



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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...