In this PHP tutorial, you shall learn how to check if the given string starts with a specific string using strpos() function, with example programs.

PHP – Check if String Starts with Substring

To check if string starts with a specific substring, use PHP built-in function strpos(). Provide the string and substring as arguments to strpos(), and if strpos() returns 0, then we can confirm that the string starts with the specific substring, else not.

The syntax of condition that checks if given string starts with specific substring is

</>
Copy
strpos($string, $substring) === 0

You can use this condition in a PHP If statement, and have conditional execution when a string starts with a specific substring or not.

Examples

1. Check if string starts with “Hello”

In this example, we will take a string, say "Hello World" in $string, and check if this string starts with $substring: "Hello" . We will use an If statement with the condition specified in the introduction above.

PHP Program

</>
Copy
<?php
$string = "Hello World";
$substring = "Hello";
if (strpos($string, $substring) === 0) {
    echo "String starts with specified Substring.";
} else {
    echo "String does not start with specified Substring.";
}
?>

Output

PHP - Check if String Starts with Substring

Conclusion

In this PHP Tutorial, we learned how to check if a string starts with a specific substring, using PHP built-in function strpos().