"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Do PHP's `startsWith()` and `endsWith()` Functions Work, and What Are Their Built-in Equivalents?

How Do PHP's `startsWith()` and `endsWith()` Functions Work, and What Are Their Built-in Equivalents?

Published on 2024-12-21
Browse:102

How Do PHP's `startsWith()` and `endsWith()` Functions Work, and What Are Their Built-in Equivalents?

Investigating the startsWith() and endsWith() Functions in PHP

To check whether a given string begins or concludes with a particular character or substring, you can implement two functions: startsWith() and endsWith().

Defining the Functions

startsWith()

function startsWith($haystack, $needle) {
    $length = strlen($needle);
    return substr($haystack, 0, $length) === $needle;
}

This function checks if the initial portion of the haystack matches the specified needle. If they do, it returns true; otherwise, it returns false.

endsWith()

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

The endsWith() function works similarly, but it examines the end of the haystack for the presence of the needle.

Example Usage

Consider the following code snippet:

$str = '|apples}';

echo startsWith($str, '|'); // Returns true
echo endsWith($str, '}'); // Returns true

In this example, the startsWith() function checks if the string begins with the pipe character '|', and it returns true because the string indeed starts with that character. Similarly, the endsWith() function verifies that the string ends with the '}' curly brace, also returning true.

PHP 8.0 and Above

In PHP 8.0 and later versions, the str_starts_with() and str_ends_with() functions provide a built-in solution for these tasks. They offer improved performance and ease of use compared to custom implementations.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3