Home >Backend Development >PHP Tutorial >How Can I Check if a String Starts or Ends with a Specific Substring in PHP?

How Can I Check if a String Starts or Ends with a Specific Substring in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-30 06:02:13472browse

How Can I Check if a String Starts or Ends with a Specific Substring in PHP?

Understanding PHP's startsWith() and endsWith() Functions

In PHP, the startsWith() and endsWith() functions provide a convenient way to determine if a string begins or terminates with a specific character or substring. Here's how you can implement them:

PHP 8.0 and Above

For PHP versions 8.0 and higher, the built-in str_starts_with and str_ends_with functions offer a straightforward solution:

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

PHP Versions Before 8.0

For PHP versions prior to 8.0, you can utilize the following custom functions:

startsWith() Function

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

echo startsWith('|apples}', '|'); // true

endsWith() Function

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

echo endsWith('|apples}', '}'); // true

These functions accept two arguments: the input string (haystack) and the character or substring (needle) to check for. They return true if the haystack starts or ends with the needle, and false otherwise.

The above is the detailed content of How Can I Check if a String Starts or Ends with a Specific Substring 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