Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP String str_starts_with() Function



The PHP String str_starts_with() function is a built-in function to perform case-sensitive searches on a given string. It basically checks if the string begins with the sub-string or not.

The function returns TRUE if the string starts with the sub-string, and FALSE otherwise.

Syntax

Below is the syntax of the PHP String str_starts_with() function −

bool str_starts_with ( string $string, string $search );

Parameters

Here are the parameters of the str_starts_with() function −

  • $string − (Required) It is the string to search in.

  • $search − (Optional) It is the specific substring to search for in the $string.

Return Value

The str_starts_with() function returns TRUE if the string begins with the given substring and FALSE otherwise.

PHP Version

The function is available from version PHP 8 onwards.

Example 1

This is the basic example of the PHP String str_starts_with() function to check if a string starts with a simple substring.

<?php
   // Define string here
   $string = "Hello, World!";
   $search = "Hello";

   echo str_starts_with($string, $search);
?>

Output

Here is the outcome of the following code −

1

Example 2

In the below PHP code we are using the str_starts_with() function and check if this function works for the case sensitivity.

<?php
   // Define string here
   $string = "hello world";
   $search = "Hello";

   // Display the result
   if (str_starts_with($string, $search)) {
      echo "The string starts with '$search'.";
   } else {
      echo "The string does not start with '$search'.";
   }
?> 

Output

This will generate the below output −

The string does not start with 'Hello'.

Example 3

In the following example, we are using the str_starts_with() function to validate the user input as per the specific rules.

<?php
   // Define username here
   $username = "admin_user123";
   $prefix = "admin_";


   // Display the result
   if (str_starts_with($username, $prefix)) {
      echo "Welcome, Admin!";
   } else {
      echo "Access Denied. Regular User.";
   }
?> 

Output

Following is the output of the above code −

Welcome, Admin!
php_function_reference.htm
Advertisements