How to add startsWith() and endsWith() functions in PHP?

Spread the love

Sometimes, we want to add startsWith() and endsWith() functions in PHP.

In this article, we’ll look at how to add startsWith() and endsWith() functions in PHP.

How to add startsWith() and endsWith() functions in PHP?

To add startsWith() and endsWith() functions in PHP, we create our own functions that call the substr function.

For instance, we write

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

to create the startsWith and endsWith functions.

In it, we call substr with $haystack with 0 and $length to check if it equals $needle.

If it is, then $haystack starts with $needle.

Likewise, we create the $endsWith function that does almost the same search except we call substr with -$length to start searching from the length of the $haystack minus $length - 1.

Conclusion

To add startsWith() and endsWith() functions in PHP, we create our own functions that call the substr function.

Leave a Reply

Your email address will not be published.