Determining if a String Begins with a Specified Substring
In various programming scenarios, verifying if a string starts with a specific substring becomes necessary. Let's consider two examples provided:
Example 1:
$string1 = 'google.com';
Question: How can we determine if $string1 starts with "http"?
Answer:
Using str_starts_with function for PHP 8 and above:
str_starts_with($string1, 'http'); // false
Using substr function for PHP 7 or older:
substr($string1, 0, 4) === "http"; // false
Example 2:
$string2 = 'http://www.google.com';
Question: How can we check if $string2 begins with "http"?
Answer:
Using str_starts_with function for PHP 8 and above:
str_starts_with($string2, 'http'); // true
Using substr function for PHP 7 or older:
substr($string2, 0, 4) === "http"; // true
In general, for any string $string and a substring $query, you can use the following logic using substr:
substr($string, 0, strlen($query)) === $query
The above is the detailed content of How to Check if a String Begins with a Specific Substring in PHP?. For more information, please follow other related articles on the PHP Chinese website!