str_starts_with and str_ends_with functions in PHP ?

In PHP 8.0+, the str_starts_with() and str_ends_with() functions were introduced to simplify checking if a string starts or ends with a specific substring. Here’s a detailed breakdown:

1. str_starts_with()

Checks if a string begins with a specified substring.

Syntax:

bool str_starts_with(string $haystack, string $needle)

Example:

$url = 'https://example.com';

// Check if URL starts with 'https://'
if (str_starts_with($url, 'https://')) {
    echo 'Secure connection';
}

2. str_ends_with()

Checks if a string ends with a specified substring.

Syntax:

bool str_ends_with(string $haystack, string $needle)

Example:

$file = 'document.pdf';

// Check if file ends with '.pdf'
if (str_ends_with($file, '.pdf')) {
    echo 'PDF file detected';
}

Key Features

Featurestr_starts_with()str_ends_with()
Case SensitivityCase-sensitiveCase-sensitive
Return Valuetrue/falsetrue/false
Empty NeedleReturns trueReturns true
PHP Version8.0+8.0+

3. Case Sensitivity

Both functions are case-sensitive:

$str = 'HelloWorld';

str_starts_with($str, 'hello'); // false
str_ends_with($str, 'world');   // false

For case-insensitive checks:

str_starts_with(strtolower($str), 'hello'); // true

4. Legacy PHP Support (Pre-8.0)

If you’re using PHP < 8.0, implement equivalent functionality:

str_starts_with Alternative:

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

str_ends_with Alternative:

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

5. Edge Cases

Empty $needle:

str_starts_with('abc', ''); // true
str_ends_with('abc', '');   // true

$needle Longer Than $haystack:

str_starts_with('a', 'abc'); // false
str_ends_with('a', 'abc');   // false

6. Multibyte Strings (UTF-8)

For multibyte characters (e.g., non-ASCII), use mb_ functions:

// Check if a UTF-8 string starts with 'ñ'
function mb_str_starts_with($haystack, $needle) {
    return mb_substr($haystack, 0, mb_strlen($needle)) === $needle;
}

Common Use Cases

  1. URL Routing:
   if (str_starts_with($_SERVER['REQUEST_URI'], '/api')) { /* Handle API */ }
  1. File Validation:
   if (str_ends_with($_FILES['file']['name'], '.jpg')) { /* Allow upload */ }
  1. Header Checks:
   if (str_starts_with($_SERVER['HTTP_USER_AGENT'], 'Mozilla')) { /* Browser detected */ }

Performance Notes

  • Built-in functions (str_starts_with/str_ends_with) are optimized and faster than manual implementations.
  • Avoid regex (preg_match) for simple checks—use these functions instead.

Comparison Table

Taskstr_starts_with()Manual substrRegex (preg_match)
ReadabilityHighMediumLow
PerformanceFastestFastSlowest
Case SensitivityYesYesConfigurable

Best Practices

  1. Use built-in functions for PHP 8.0+.
  2. For case-insensitive checks, normalize case first:
   str_starts_with(strtolower($str), strtolower($prefix))
  1. Combine with empty() for robustness:
   if (!empty($needle) && str_starts_with($haystack, $needle)) { ... }

These functions provide a clean and efficient way to handle common string prefix/suffix checks in PHP.

Leave a Reply

Your email address will not be published. Required fields are marked *