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

Barbara Streisand
Release: 2024-10-30 14:09:02
Original
490 people have browsed it

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';
Copy after login

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
Copy after login

Using substr function for PHP 7 or older:

substr($string1, 0, 4) === "http"; // false
Copy after login

Example 2:

$string2 = 'http://www.google.com';
Copy after login

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
Copy after login

Using substr function for PHP 7 or older:

substr($string2, 0, 4) === "http"; // true
Copy after login

In general, for any string $string and a substring $query, you can use the following logic using substr:

substr($string, 0, strlen($query)) === $query
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!