Home >Backend Development >PHP Tutorial >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?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-18 05:50:10687browse

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.

The above is the detailed content of How Do PHP's `startsWith()` and `endsWith()` Functions Work, and What Are Their Built-in Equivalents?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn