In this PHP tutorial, you shall learn how to check if the given string starts with “http” using strpos() function, with example programs.
PHP – Check if String Starts with http
To check if string starts with “http”, use PHP built-in function strpos(). strpos() takes the string and substring as arguments and returns 0, if the string starts with “http”, else not.
This kind of check is useful when you want to verify if given string is an URL or not.
The syntax of condition that checks if given string starts with “http” is
strpos($string, "http") === 0
You can use this condition in a PHP If statement, and have conditional execution when a string starts with “http” or not.
Examples
1. Check if String Starts with “http” in PHP
In this example, we will take a string, say "https://www.tutorialkart.com/"
in $string, and check if this string starts with "http"
. We will use an If statement with the condition specified in the introduction above.
PHP Program
<?php $string = "https://www.tutorialkart.com/"; if (strpos($string, "http") === 0) { echo "\"{$string}\" starts with \"http\"."; } else { echo "\"{$string}\" does not start with \"http\"."; } ?>
Output
Conclusion
In this PHP Tutorial, we learned how to check if a string starts with a specific substring, using PHP built-in function strpos().