🐶
PHP

PHP startsWith() and endsWith() Functions Explained

By Filip on 10/16/2024

Learn how to efficiently check if a string starts or ends with specific characters using the powerful startsWith() and endsWith() functions in PHP.

PHP startsWith() and endsWith() Functions Explained

Table of Contents

Introduction

In PHP, determining if a string starts or ends with a specific substring is a common task. PHP offers built-in functions to simplify this process, making string manipulation more efficient. This article will guide you through these functions and provide examples of how to use them effectively.

Step-by-Step Guide

PHP provides built-in functions for checking if a string starts or ends with a specific substring:

1. str_starts_with()

This function checks if a string starts with a given substring.

$string = "Hello world!";
if (str_starts_with($string, "Hello")) {
    echo "The string starts with 'Hello'";
}

2. str_ends_with()

This function checks if a string ends with a given substring.

$string = "Hello world!";
if (str_ends_with($string, "world!")) {
    echo "The string ends with 'world!'";
}

Before PHP 8:

If you're using an older PHP version, you can use substr_compare() to achieve similar functionality:

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

function endsWith($haystack, $needle) {
    return substr_compare($haystack, $needle, -strlen($needle)) === 0;
}

Case-insensitive checks:

For case-insensitive checks, you can convert both the string and the substring to lowercase (or uppercase) using strtolower() (or strtoupper()) before comparison:

$string = "Hello world!";
if (str_starts_with(strtolower($string), strtolower("hello"))) {
    echo "The string starts with 'hello' (case-insensitive)";
}

Code Example

This PHP code demonstrates how to check if a string starts or ends with a specific substring. It uses the str_starts_with() and str_ends_with() functions for PHP 8 and above. For older versions, it defines custom functions startsWith() and endsWith() to achieve the same functionality. The code also shows how to perform case-insensitive checks using strtolower().

<?php

// PHP 8 and above

$string = "Hello world!";

// Check if the string starts with "Hello"
if (str_starts_with($string, "Hello")) {
    echo "The string starts with 'Hello'" . PHP_EOL;
}

// Check if the string ends with "world!"
if (str_ends_with($string, "world!")) {
    echo "The string ends with 'world!'" . PHP_EOL;
}

// Before PHP 8

if (version_compare(PHP_VERSION, '8.0.0') < 0) {

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

    function endsWith($haystack, $needle) {
        return substr_compare($haystack, $needle, -strlen($needle)) === 0;
    }

    // Check if the string starts with "Hello"
    if (startsWith($string, "Hello")) {
        echo "The string starts with 'Hello' (using custom function)" . PHP_EOL;
    }

    // Check if the string ends with "world!"
    if (endsWith($string, "world!")) {
        echo "The string ends with 'world!' (using custom function)" . PHP_EOL;
    }
}

// Case-insensitive checks

// Check if the string starts with "hello" (case-insensitive)
if (str_starts_with(strtolower($string), strtolower("hello"))) {
    echo "The string starts with 'hello' (case-insensitive)" . PHP_EOL;
}

?>

This code example demonstrates:

  1. Using str_starts_with() and str_ends_with() in PHP 8 and above.
  2. Defining custom functions startsWith() and endsWith() for PHP versions before 8.
  3. Performing case-insensitive checks using strtolower().

This comprehensive example covers all the scenarios mentioned in the article and provides a clear understanding of how to check for substrings at the beginning or end of a string in PHP.

Additional Notes

  • Efficiency: For simple checks, str_starts_with() and str_ends_with() are generally more efficient than using substr_compare(). This is because they are specifically designed for this purpose.
  • Alternatives: While the provided functions are the most common and readable, other methods exist for achieving the same result. These include using regular expressions, strpos(), and string manipulation functions like substr(). However, these methods might be less efficient or less readable for this specific task.
  • Practical Applications: Checking if a string starts or ends with a specific substring is useful in various scenarios, such as:
    • Validating input: Ensuring user input starts with a specific prefix or ends with a specific file extension.
    • String manipulation: Extracting information from strings based on specific delimiters.
    • Routing: Determining the appropriate action based on the beginning or ending part of a URL.
  • Error Handling: While not explicitly shown in the examples, it's good practice to check if the $needle (substring) is empty before performing the comparison. This prevents unexpected behavior and potential errors.
  • Multibyte Strings: When working with multibyte strings (e.g., UTF-8), consider using mb_str_starts_with() and mb_str_ends_with() for accurate results. These functions are specifically designed to handle multibyte characters correctly.

Summary

Function Description PHP Version Case-Sensitive
str_starts_with($string, $substring) Checks if $string starts with $substring PHP 8+ Yes
str_ends_with($string, $substring) Checks if $string ends with $substring PHP 8+ Yes
substr_compare($haystack, $needle, 0, strlen($needle)) === 0 Custom function for str_starts_with functionality Before PHP 8 Yes
substr_compare($haystack, $needle, -strlen($needle)) === 0 Custom function for str_ends_with functionality Before PHP 8 Yes

Note: For case-insensitive checks, use strtolower() or strtoupper() on both the string and substring before comparison.

Conclusion

In conclusion, PHP provides straightforward methods for determining if a string starts or ends with a particular substring. While PHP 8 and later offer dedicated functions like str_starts_with() and str_ends_with() for this purpose, earlier versions can achieve similar results using substr_compare(). The examples provided in this article offer a clear understanding of how to implement these checks, including case-insensitive comparisons. Understanding these techniques empowers developers to efficiently handle and manipulate strings, a fundamental aspect of web development with PHP.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait