Home >Backend Development >PHP Tutorial >PHP how to check if a string starts with a given substring
php editor Zimo teaches you today how to use PHP to check whether a string starts with a given substring. In PHP, we can use the strpos() function to achieve this function, which can return the position of the substring in the original string and determine whether it starts with the specified substring by judging whether it is 0. Let’s take a look at the specific code implementation!
Check if a string starts with a given substring
In php there are several ways to check if a string starts with a given substring. Here are some of the most common methods:
1. strpos() function
strpos() function can be used to find the position of a given substring in a string. If the substring occurs at the beginning of the string, the function returns 0.
$string = "Hello world"; $substring = "Hello"; if (strpos($string, $substring) === 0) { echo "The string starts with the substring."; }
2. substr() function
The substr() function can extract a substring from a string. If the extracted substring matches the given substring, it means that the string starts with that substring.
$string = "Hello world"; $substring = "Hello"; if (substr($string, 0, strlen($substring)) === $substring) { echo "The string starts with the substring."; }
3. preg_match() function
Thepreg_match() function can perform pattern matching in a string based on a given regular expression. The following regular expression can match a string starting with a given substring:
^substring
Among them, the ^ symbol means matching the beginning of the string.
$string = "Hello world"; $substring = "Hello"; if (preg_match("/^" . $substring . "/", $string)) { echo "The string starts with the substring."; }
4. String::startsWith() method
In PHP 8.0 and higher, the String::startsWith() method is added, which is specifically used to check whether a string starts with a given substring.
$string = "Hello world"; $substring = "Hello"; if ($string->startsWith($substring)) { echo "The string starts with the substring."; }
Performance comparison
Different methods may vary in performance, depending on the length of the string, the length of the substring being found, and the number of checks to be performed. However, in most cases, the strpos() function is the fastest because it directly locates the first occurrence of the substring.
The above is the detailed content of PHP how to check if a string starts with a given substring. For more information, please follow other related articles on the PHP Chinese website!