How To Use StartsWith() And EndsWith() Functions In PHP?

Published October 7, 2024

Problem: Comparing String Prefixes and Suffixes in PHP

PHP developers often need to check if a string starts or ends with specific characters. The startsWith() and endsWith() functions let you compare string prefixes and suffixes. Learning how to use these functions can help you handle string tasks in PHP scripts.

PHP 8.0 and Later: Built-in Functions

PHP 8.0 added built-in functions for checking string prefixes and suffixes, making these operations easier.

Using str_starts_with() Function

The str_starts_with() function checks if a string starts with a given substring. Its syntax is:

str_starts_with(string $haystack, string $needle): bool

Here's an example:

$str = '|apples}';
$result = str_starts_with($str, '|');
var_dump($result); // Output: bool(true)

Tip: Case Sensitivity in str_starts_with()

Remember that str_starts_with() is case-sensitive. If you need a case-insensitive check, convert both strings to the same case before comparison:

$str = 'Apple pie';
$result = str_starts_with(strtolower($str), 'apple');
var_dump($result); // Output: bool(true)

Using str_ends_with() Function

The str_ends_with() function checks if a string ends with a given substring. Its syntax is:

str_ends_with(string $haystack, string $needle): bool

Here's an example:

$str = '|apples}';
$result = str_ends_with($str, '}');
var_dump($result); // Output: bool(true)

Both functions return a boolean value: true if the string starts or ends with the specified substring, and false otherwise. These built-in functions offer a simple way to perform prefix and suffix checks in PHP 8.0 and later versions.

Pre-PHP 8.0: Custom Functions

For PHP versions before 8.0, you can create custom functions to check string prefixes and suffixes.

Implementing startsWith() Function

The startsWith() function checks if a string begins with a specific substring. Here's how to implement it:

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

Function logic:

  1. Get the length of the needle (substring to check for).
  2. Extract a substring from the haystack (main string) with the same length as the needle, starting from the beginning.
  3. Compare the extracted substring with the needle.

Parameters and return value:

  • $haystack: The main string to check.
  • $needle: The substring to look for at the start of the haystack.
  • Returns: true if the haystack starts with the needle, false otherwise.

Example: Using startsWith() Function

$text = "Hello, World!";
$prefix = "Hello";

if (startsWith($text, $prefix)) {
    echo "The string starts with 'Hello'";
} else {
    echo "The string does not start with 'Hello'";
}

Implementing endsWith() Function

The endsWith() function checks if a string ends with a specific substring. Here's the implementation:

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

Function logic:

  1. Get the length of the needle.
  2. If the needle is empty, return true (an empty string is considered to end any string).
  3. Extract a substring from the haystack with the same length as the needle, starting from the end.
  4. Compare the extracted substring with the needle.

Parameters and return value:

  • $haystack: The main string to check.
  • $needle: The substring to look for at the end of the haystack.
  • Returns: true if the haystack ends with the needle, false otherwise.

Tip: Case-Insensitive Checks

To perform case-insensitive checks, you can modify the functions to use strtolower() on both the haystack and needle:

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

function endsWithInsensitive($haystack, $needle) {
    $length = strlen($needle);
    if ($length == 0) {
        return true;
    }
    return strtolower(substr($haystack, -$length)) === strtolower($needle);
}

These custom functions provide a way to check string prefixes and suffixes in PHP versions before 8.0, mimicking the functionality of the built-in functions introduced later.

Practical Examples

Validating File Extensions

The endsWith() function helps check file extensions. You can use it to validate uploaded files or filter files by type. Here's an example of using endsWith() for file type checking:

function isImageFile($filename) {
    $allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif'];
    foreach ($allowedExtensions as $extension) {
        if (endsWith(strtolower($filename), $extension)) {
            return true;
        }
    }
    return false;
}

// Usage
$file1 = "image.jpg";
$file2 = "document.pdf";

echo isImageFile($file1) ? "File 1 is an image" : "File 1 is not an image";
echo "\n";
echo isImageFile($file2) ? "File 2 is an image" : "File 2 is not an image";

This function checks if a filename ends with an allowed image extension. It uses strtolower() to make the check case-insensitive.

Tip: Security Consideration

When validating file extensions, also check the file's content using functions like mime_content_type() or finfo_file() to prevent potential security risks from disguised malicious files.

URL Protocol Verification

The startsWith() function helps check URL protocols. You can use it to validate or group URLs by their protocols. Here's an example:

function getUrlProtocol($url) {
    $protocols = ['http://', 'https://', 'ftp://'];
    foreach ($protocols as $protocol) {
        if (startsWith(strtolower($url), $protocol)) {
            return $protocol;
        }
    }
    return 'Unknown';
}

// Usage
$url1 = "https://www.example.com";
$url2 = "ftp://ftp.example.com";
$url3 = "www.example.com";

echo "URL 1 protocol: " . getUrlProtocol($url1) . "\n";
echo "URL 2 protocol: " . getUrlProtocol($url2) . "\n";
echo "URL 3 protocol: " . getUrlProtocol($url3);

This function checks if a URL starts with a common protocol. It returns the matched protocol or 'Unknown' if no match is found. The strtolower() function makes the check case-insensitive.

These examples show how you can use startsWith() and endsWith() functions in PHP for common string comparison tasks.

Example: Validating Email Domains

function isCompanyEmail($email) {
    $allowedDomains = ['@company.com', '@company.org'];
    foreach ($allowedDomains as $domain) {
        if (endsWith(strtolower($email), $domain)) {
            return true;
        }
    }
    return false;
}

// Usage
$email1 = "user@company.com";
$email2 = "user@gmail.com";

echo isCompanyEmail($email1) ? "Email 1 is a company email" : "Email 1 is not a company email";
echo "\n";
echo isCompanyEmail($email2) ? "Email 2 is a company email" : "Email 2 is not a company email";