Home >Backend Development >PHP Tutorial >How Can PHP's `startsWith()` and `endsWith()` (or `str_starts_with()` and `str_ends_with()`) Efficiently Check String Prefixes and Suffixes?

How Can PHP's `startsWith()` and `endsWith()` (or `str_starts_with()` and `str_ends_with()`) Efficiently Check String Prefixes and Suffixes?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-18 05:15:10165browse

How Can PHP's `startsWith()` and `endsWith()` (or `str_starts_with()` and `str_ends_with()`) Efficiently Check String Prefixes and Suffixes?

Determining String Prefixes and Suffixes with startWith() and endsWith() in PHP

Introduction:
In string manipulation tasks, it is often necessary to check whether a string starts or ends with specific characters or substrings. PHP provides two very useful functions, startWith() and endsWith(), which enable developers to perform such comparisons with ease.

startWith() and endsWith() Functions:
The startWith() and endsWith() functions take a string as their first argument and a prefix or suffix as their second argument. They return a boolean value, with true indicating that the string meets the specified condition and false otherwise.

Implementation:

PHP 8.0 and Higher:
In PHP 8.0 and later versions, the str_starts_with and str_ends_with functions can be used to check for prefixes and suffixes respectively.

str_starts_with($str, '|');  // true if $str starts with '|'

PHP Prior to 8.0:
If you're using PHP versions earlier than 8.0, custom functions can be implemented to achieve the same functionality:

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;
}

Example Usage:

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

The above is the detailed content of How Can PHP's `startsWith()` and `endsWith()` (or `str_starts_with()` and `str_ends_with()`) Efficiently Check String Prefixes and Suffixes?. 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