Home > Article > Backend Development > 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)
For example:
<code class="php">$string1 = 'google.com'; $string2 = 'http://www.google.com'; var_dump(str_starts_with($string2, 'http')); // true</code>
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
For instance:
<code class="php">substr($string2, 0, 4) === "http"; // true</code>
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>
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!