PHP – Implement startsWith() and endsWith() functions
This post shows you how to implement startsWith
and endsWith
functions in PHP.
1. startsWith() function
startsWith.php
function startsWith($haystack, $needle)
{
$length = strlen($needle);
return ($needle === '')
|| (substr($haystack, 0, $length) === $needle);
}
The function startsWith
function that checks whether the string starts with a specified prefix, i.e. it returns true
if the $needle
string is a prefix of the $haystack
string, false
if it does not.
Code example:
$message = 'Foo and Bar';
if (startsWith($message, 'Foo')) {
echo 'The message starts with Foo';
} else {
echo 'The message does not start with Foo';
}
Output:
The message starts with Foo
2. endsWith() function
endsWith.php
function endsWith($haystack, $needle)
{
$length = strlen($needle);
return ($needle === '')
|| (substr($haystack, -$length) === $needle);
}
The endsWith
function that checks whether the string ends with a specified suffix, i.e. it returns true
if the $needle
string is a suffix of the $haystack
string, false
if it does not.
Code example:
$message = 'Foo and Bar';
if (endsWith($message, 'Bar')) {
echo 'The message ends with Bar';
} else {
echo 'The message does not end with Bar';
}
Output:
The message ends with Bar