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
Release: 2024-12-19 21:25:14
Original
471 people have browsed it

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;
}
Copy after login

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
Copy after login

endsWith() Function:

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

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template