This is a predefined function in PHP 8 that is used to perform case-sensitive searches on a given string. str_starts_with() generally checks for the string if it is beginning with the substring or not. If the string begins with the substring then str_starts_with() will return TRUE otherwise it will return FALSE.
Syntax:
str_starts_with($string, $substring)
Parameters:
- $string: This parameter refers to the string whose starting string needs to be checked.
- $substring: This parameter refers to the string that needs to be checked.
Return Type: If the string begins with the substring then str_starts_with() will return TRUE otherwise it will return FALSE.
Key Features:
- str_starts_with() is case-sensitive in nature.
- str_starts_with() always returns a Boolean value.
- str_starts_with() can be used to check the beginning of both a character as well as a string.
- str_starts_with() is not supported on versions of PHP smaller than 8.
Example 1: In the below program, we have created three variables $name to store a name of a type string, $beginsWith to store the substring that needs to be checked with $name, and $result to store the result of the expression evaluated on basis of str_starts_with(). If the string $name will begin with the substring $beginsWith then str_starts_with() will return TRUE otherwise it will return FALSE and the value for $result will be assigned accordingly.
PHP
<?php $name = 'Saurabh Singh' ; $beginsWith = 'S' ; $result = str_starts_with( $name , $beginsWith ) ? 'is' : 'is not' ; echo "The string \"$name\" $result starting with $beginsWith" ; ?> |
Output:
The string "Saurabh Singh" is starting with S
Example 2: In the first example, we took the beginning character of the sentence for searching. In this example, we have taken a complete word with which the sentence begins and it will also return TRUE within the if condition, and further the conditional part will be executed accordingly.
PHP
<?php $sentance = 'The Big Brown Fox' ; $beginsWith = 'The' ; if (str_starts_with( $sentance , $beginsWith ) ) { echo "The string \"$sentance\" begins with \"$beginsWith\" " ; } else { echo "The string \"$sentance\" does not begins with \"$beginsWith\" " ; } ?> |
Output :
The string "The Big Brown Fox" begins with "The"
Reference: https://www.php.net/manual/en/function.str-starts-with.php