Home >Backend Development >PHP Tutorial >How to Check if a String Begins with a Specific Substring in PHP?

How to Check if a String Begins with a Specific Substring in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 14:09:02627browse

How to Check if a String Begins with a Specific Substring in PHP?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn