Home >Backend Development >PHP Tutorial >How to Implement `startsWith()` and `endsWith()` Functions in PHP?

How to Implement `startsWith()` and `endsWith()` Functions in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-12-19 21:25:14474browse

How to Implement `startsWith()` and `endsWith()` Functions in PHP?

Implementing startsWith() and endsWith() Functions in PHP

In PHP, you can create custom functions to check if a string begins or ends with a specific character or string. Here's how you can write these functions:

startsWith() Function:

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

This function takes two parameters: the haystack (the string to check) and the needle (the character or string you're looking for at the start). It checks if the substring of the haystack starting from position 0 has a length equal to the needle and matches the needle. If true, it means the string starts with the needle.

Example:

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

endsWith() Function:

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

This function works similarly, except it checks the substring of the haystack from the end of the string (-$length). If the substring matches the needle, it means the string ends with the needle.

Example:

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

PHP 8.0 and Higher:

From PHP 8.0 onwards, there are built-in functions str_starts_with and str_ends_with that provide the same functionality.

var_dump(str_starts_with('|apples}', '|')); // Returns true
var_dump(str_ends_with('|apples}', '}')); // Returns true

The above is the detailed content of How to Implement `startsWith()` and `endsWith()` Functions in PHP?. 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