PHP - String str_starts_with() Function
The PHP String str_starts_with() function is used to check if a string starts with a given substring. It performs case-sensitive check and returns true if the string starts with specified substring, else returns false.
Note: It is a binary-safe function. This function is new in PHP 8.
Syntax
str_starts_with(str1, str2)
Parameters
str1 |
Required. Specify the string to check |
str2 |
Required. Specify the substring to check whether the string starts with or not. |
Return Value
Returns true if the string starts with specified substring, else returns false.
Example:
In the below example, str_starts_with() function is used to check whether the given string starts with specified substring or not.
<?php $str1 = "Hello"; //checking whether $str1 starts with empty string if(str_starts_with($str1, "")) { echo "Every string starts with an empty string.\n"; } //checking whether $str1 starts with "lo" if(str_starts_with($str1, "He")) { echo "$str1 starts with 'He'.\n"; } //case-sensitive check -checking //whether $str1 starts "HE" if(!str_starts_with($str1, "HE")) { echo "str_starts_with() performs case-sensitive check.\n"; } ?>
The output of the above code will be:
Every string starts with an empty string. Hello starts with 'He'. str_starts_with() performs case-sensitive check.
❮ PHP String functions