PHP Function Reference

PHP str_starts_with() Function



The PHP 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 search in.
str2 Required. Specify the substring to search in str1.

Return Value

Returns true if str1 starts with str2, else returns false.

Example:

In the example below, 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";
}
?>

The output of the above code will be:

Every string starts with an empty string.
Hello starts with 'He'.

Example:

Consider one more example which illustrates on case-sensitive check using str_starts_with() function.

<?php
$str = "Hello John";

//checking whether $str starts with "HELLO"
if(str_starts_with($str, "HELLO")) {
  echo 'The string starts with "HELLO".';
} else {
  echo 'The string does not start with "HELLO". ';
  echo "\nCase does not match."; 
}
?>

The output of the above code will be:

The string does not start with "HELLO". 
Case does not match.

❮ PHP String Reference