How do you check if a string starts with a specific substring in PHP?

Hello Friends Today, through this tutorial, I will tell you How do you check if a string starts with a specific substring in PHP With Example? In PHP, you can check if a string starts with a specific substring using the `substr()` function along with comparison or by using the `substr_compare()` function. Additionally, PHP 8 introduced a dedicated function `str_starts_with()` for this purpose. Here’s how you can achieve it using each method:

1. Using `substr()` and comparison:

<?php
$string = "This is a sample string";
$substring = "This";
if (substr($string, 0, strlen($substring)) === $substring) {
echo "The string starts with '$substring'.";
} else {
echo "The string does not start with '$substring'.";
}
?>

2. Using `substr_compare()`:

<?php
$string = "This is a sample string";
$substring = "This";
if (substr_compare($string, $substring, 0, strlen($substring)) === 0) {
echo "The string starts with '$substring'.";
} else {
echo "The string does not start with '$substring'.";
}
?>

3. Using `str_starts_with()` (PHP 8 and later):

<?php
$string = "This is a sample string";
$substring = "This";
if (str_starts_with($string, $substring)) {
echo "The string starts with '$substring'.";
} else {
echo "The string does not start with '$substring'.";
}
?>

These methods will output:

The string starts with 'This'.

Each of these methods achieves the same result, but using `str_starts_with()` is more concise and clearer in indicating the intention of checking if a string starts with a specific substring.