Check if a string starts with a particular string in PHP

Check if a string starts with a particular string in PHP

Checking whether a string starts with a particular string in PHP is a common task in web development. Fortunately, PHP provides built-in functions to accomplish this task quickly and easily.

Using substr() function

The easiest way to check if a string starts with a particular string in PHP is by using the substr() function. This function returns a part of the string starting from the specified position.

The following code demonstrates how to use the substr() function to check if a string starts with a particular string:

<?php
$string = "Hello world!";
$prefix = "Hello";

if (substr($string, 0, strlen($prefix)) === $prefix) {
    echo "The string starts with the prefix.";
} else {
    echo "The string does not start with the prefix.";
}
?>

The output of the code above will be:

The string starts with the prefix.

Using strpos() function

Another way to check if a string starts with a particular string in PHP is by using the strpos() function. This function finds the position of the first occurrence of a substring in a string.

The following code demonstrates how to use the strpos() function to check if a string starts with a particular string:

<?php
$string = "Hello world!";
$prefix = "Hello";

if (strpos($string, $prefix) === 0) {
    echo "The string starts with the prefix.";
} else {
    echo "The string does not start with the prefix.";
}
?>

The output of the code above will be:

The string starts with the prefix.

Using str_starts_with() function

Starting from PHP 8.0.0, you can also use the str_starts_with() function to check if a string starts with a particular string. This function is a simple and intuitive way to perform this task.

The following code demonstrates how to use the str_starts_with() function to check if a string starts with a particular string:

<?php
$string = "Hello world!";
$prefix = "Hello";

if (str_starts_with($string, $prefix)) {
    echo "The string starts with the prefix.";
} else {
    echo "The string does not start with the prefix.";
}
?>

The output of the code above will be:

The string starts with the prefix.

Using str_starts_with() function is a simple and readable way to check if a string starts with a particular string. However, keep in mind that this function is only available in PHP 8.0.0 and later versions.

Overall, these methods are reliable ways to check if a string starts with a particular string in PHP. You can choose the one that fits your needs and coding style best.

Leave a Reply

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