PHP str_starts_with

Summary: in this tutorial, you’ll learn how to use the PHP str_starts_with() function to check if a string starts with a substring.

Introduction to the PHP str_starts_with() function

The str_starts_with() function performs a case-senstive search and checks if a string starts with a substring:

str_starts_with ( string $haystack , string $needle ) : bool
Code language: PHP (php)

The str_starts_with() function has two parameters:

  • $haystack is the input string to check.
  • $needle is the substring to search for in the input string.

The str_starts_with() function returns true if the $haystack starts with the $needle or false otherwise.

The str_starts_with() function has been available since PHP 8.0.0. If you use a lower version of PHP, you can polyfill the function like this:

<?php if (!function_exists('str_starts_with')) { function str_starts_with($haystack, $needle) { return (string)$needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0; } }
Code language: PHP (php)

PHP str_starts_with() function examples

Let’s take some examples of using the PHP str_starts_with() function.

1) Using PHP str_starts_with() function with single character example

The following example uses the PHP str_starts_with() function to check if the string 'PHP tutorial' starts with the letter 'P':

<?php $str = 'PHP tutorial'; $substr = 'P'; $result = str_starts_with($str, $substr) ? 'is' : 'is not'; echo "The $str $result starting with $substr";
Code language: PHP (php)

Output:

The PHP tutorial is starting with P
Code language: PHP (php)

2) Using the PHP str_starts_with() function with multiple characters example

The following example uses the PHP str_starts_with() function to check if the string 'PHP tutorial' starts with the string 'PHP':

<?php $str = 'PHP tutorial'; $substr = 'PHP'; $result = str_starts_with($str, $substr) ? 'is' : 'is not'; echo "The $str $result starting with $substr";
Code language: PHP (php)

Output:

The PHP tutorial is starting with PHP
Code language: PHP (php)

2) Case-sensitive example

It’s important to keep in mind that the str_starts_with() function performs a case-sensitive search. For example:

<?php $str = 'PHP tutorial'; $substr = 'php'; $result = str_starts_with($str, $substr) ? 'is' : 'is not'; echo "The $str $result starting with $substr";
Code language: PHP (php)

Output:

The PHP tutorial is not starting with php
Code language: PHP (php)

Summary

  • Use the PHP str_starts_with() function to perform a case-sensitive search and check if a string starts with a substring.
Did you find this tutorial useful?