Check if String Starts or Ends with Substring in PHP 8.0

Check if String Starts or Ends with Substring in PHP 8.0

Checking whether a string starts or ends with a given substring are very common tasks. In versions prior to PHP 8.0, this functionality can be implemented using various string functions such as substr, strpos, etc.

Since PHP 8.0, we can use the str_starts_with and str_ends_with functions to check if a string starts or ends with a given substring.

<?php

$text = 'Hello world';

if (str_starts_with($text, 'Hello')) {
    echo 'Found';
}

if (str_ends_with($text, 'world')) {
    echo 'Found';
}

Note that str_starts_with and str_ends_with functions are case-sensitive. In the following code, a substring was not found in both cases:

<?php

$text = 'Hello world';

if (str_starts_with($text, 'hello')) {
    echo 'Found';
} else {
    echo 'Was not found because the case does not match';
}

if (str_ends_with($text, 'World')) {
    echo 'Found';
} else {
    echo 'Was not found because the case does not match';
}

Leave a Comment

Cancel reply

Your email address will not be published.