PHP: Check if a string starts or ends with another string

Updated: January 10, 2024 By: Guest Contributor Post a comment

Overview

Working with strings is a fundamental part of programming in PHP. Frequently, developers need to determine whether a string begins with or concludes with a specific set of characters. This article provids a practical guide with examples, showcasing how to perform these checks in PHP.

Introduction to String Operations in PHP

In PHP, strings are sequences of characters, and checking their start or end patterns is a common task. It might be for validating inputs, routing, or simply parsing data. PHP provides built-in functions to help with these, along with less direct methods that give you more control and flexibility.

Before we proceed, let’s understand some basic built-in string functions provided by PHP:

  • substr(): Returns a part of a string.
  • strpos(): Finds the position of the first occurrence of a substring in a string.
  • strrpos(): Finds the position of the last occurrence of a substring in a string.
  • strncmp(): Compares two strings but stops comparing after a specific number of characters.
  • str_ends_with(): Checks if a string ends with a given substring (in PHP 8 and above).
  • str_starts_with(): Checks if a string starts with a given substring (in PHP 8 and above).

These functions form the basis of string comparisons in PHP. However, depending on your PHP version, some of these functions may not be available. Let’s start with the more manual methods and work towards the built-in functions for PHP 8.

Basic String Checking with substr()

The substr() function is a versatile tool that enables you to extract a substring from a string. This can be used to check if a string starts or ends with another string by comparing the extracted substring to the pattern.

// Check if a string starts with 'hello' using substr()
function startsWithSubstr($string, $startString) {
    return substr($string, 0, strlen($startString)) === $startString;
}

// Check if a string ends with 'world' using substr()
function endsWithSubstr($string, $endString) {
    return substr($string, -strlen($endString)) === $endString;
}

In the code above, startsWithSubstr() uses substr() to get the first characters of the string based on the length of the starting pattern we’re looking for and compares it to the pattern provided. Similarly, endsWithSubstr() uses a negative start position to get the end portion of the string for comparison.

Using strpos() and strrpos() for Positioning

While substr() extracts a substring, strpos() and strrpos() functions come handy when you want to check for the position of the start or end pattern instead of extracting it. Here’s how you can use these functions:

// Check if a string starts with 'hello' using strpos()
function startsWithStrpos($string, $startString) {
    return strpos($string, $startString) === 0;
}

// Check if a string ends with 'world' using strrpos()
function endsWithStrrpos($string, $endString) {
    $position = strrpos($string, $endString);
    if ($position === FALSE) {
        return FALSE;
    }
    return $position === strlen($string) - strlen($endString);
}

The startsWithStrpos() function returns true if the pattern is at the start of the string, since strpos() would return 0 (which is the first position). The endsWithStrrpos() checks the last position of the pattern and compares it against the calculated position it would be if the string did end with our target pattern.

Comparing Start and End Using strncmp() and strcasecmp()

In some cases, you may want to compare a certain number of characters at the beginning of two strings. This is where strncmp() comes into play. Additionally, for case-insensitive checks, we can use strcasecmp().

// Check if a string starts with 'hello' using strncmp()
function startsWithStrncmp($string, $startString) {
    return strncmp($string, $startString, strlen($startString)) === 0;
}

// Case-insensitive check if a string ends with 'world'
function endsWithStrcasecmp($string, $endString) {
    return strcasecmp(substr($string, -strlen($endString)), $endString) === 0;
}

The above functions employ strncmp() and strcasecmp() to match the start and end patterns of strings. It’s essential to note that strcasecmp() ignores the case of characters, making it useful for case-insensitive comparisons.

Leveraging PHP 8’s str_starts_with() and str_ends_with()

In PHP 8, two new functions were introduced to make starting and ending string checks really straightforward. Here’s how simple it is to use them:

// PHP 8 or higher required
function startsWith($string, $startString) {
    return str_starts_with($string, $startString);
}

function endsWith($string, $endString) {
    return str_ends_with($string, $endString);
}

These functions do what their names suggest – check if a string starts or ends with a specified pattern. They are easy to use and understand.

Conclusion

This article covered various methods to check if a PHP string starts or ends with another string. While the newer PHP 8 functions provide a concise approach, knowing the alternative methods is invaluable for working with prior PHP versions or in situations that require a more manual control. Apply these techniques to write clean and efficient PHP code that handles string comparisons effectively.