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

How to Check if a String Starts with a Specific String in PHP?

Patricia Arquette
Release: 2024-10-31 05:50:02
Original
460 people have browsed it

How to Check if a String Starts with a Specific String in PHP?

Checking If a String Begins with a Specific String

Determining whether a string commences with a particular sequence of characters can be essential in various programming scenarios. One common use case involves verifying the presence of HTTP protocols in URLs. This article offers comprehensive solutions for this task using both modern and legacy PHP versions.

Modern PHP (Version 8 and Above):

PHP 8 introduces the str_starts_with function, which provides a convenient way to check if a string starts with another. Its syntax is straightforward:

str_starts_with($string, $prefix)
Copy after login

For example:

<code class="php">$string1 = 'google.com';
$string2 = 'http://www.google.com';

var_dump(str_starts_with($string2, 'http')); // true</code>
Copy after login

Legacy PHP (Version 7 and Below):

In older PHP versions, the substr function can be employed to achieve the same goal. substr extracts a portion of a string, allowing you to compare the first few characters with the specified prefix.

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

For instance:

<code class="php">substr($string2, 0, 4) === "http"; // true</code>
Copy after login

This method ensures that the comparison only considers the specified number of characters from the beginning of the string. You can modify the length argument to check longer prefixes.

Additional Considerations:

When dealing with protocols, it's crucial to ensure that the comparison is specific enough to avoid matching unintended strings. For example, if you want to make sure that a string starts with "http://" and not just "http," use the following:

<code class="php">substr($string, 0, 7) === "http://";</code>
Copy after login

This ensures that the comparison only matches strings that explicitly start with "http://", excluding other variations such as "https" or "http-protocol.com."

The above is the detailed content of How to Check if a String Starts with a Specific String 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