verify, if the string starts with given substring

Viewed 45727

I have a string in $str variable.

How can I verify if it starts with some word?


Example:

$str = "http://somesite.com/somefolder/somefile.php";

When I wrote the following script returns yes

if(strpos($str, "http://") == '0') echo "yes";

BUT it returns yes even when I wrote

if(strpos($str, "other word here") == '0') echo "yes";

I think strpos returns zero if it can't find substring too (or a value that evaluates to zero).

So, what can I do if I want to verify if word is in the start of string? Maybe I must use === in this case?

10 Answers

Starting with PHP 8 (2020-11-24), you can use str_starts_with:

if (str_starts_with($str, 'http://')) {
   echo 'yes';
}

PHP 8 has now a dedicated function str_starts_with for this.

if (str_starts_with($str, 'http://')) {
   echo 'yes';
}
Related