str_starts_with and str_ends_with function in PHP 8

PHPServer Side ProgrammingProgramming

str_starts_with and str_ends_with function are added in PHP 8 to check if a given string starts or ends with another string or not. If it starts and ends with another string, it returns true, otherwise false.

Example

str_starts_with('hello haystack', 'hello'); //starts string found 'True'
str_starts_with('hello haystack', 'stack'); //ends string found 'True'


str_starts_with('hello haystack', 'hay'); //starts string found 'False'
str_starts_with('hello haystack', 'hay'); //ends string found 'False'

str_starts_with() function in PHP 8

This function checks if a given string starts with the string needle. It returns true if the first string is found, otherwise false.

str_starts_with(string $haystack, string $needle): bool

Example : using str_starts_with() function.

<?php
   if (str_starts_with('hellohaystack', "hello")) {
      echo "string starts with hello";
   }
?>

Output

String starts with 'hello'

Note: If the given first start string is not found in the second string, it returns false.

str_ends_with() function in PHP 8

This function checks if a given string ends with the string needle. It returns true if the given string ends found, otherwise false.

str_ends_with(string $haystack, string $needle):bool

Example : using str_ends_with() function

<?php
   if (str_ends_with('hellohaystack', "stack")) {
      echo "string ends with stack";
   }
?>

Output

String ends with 'stack'
raja
Published on 01-Apr-2021 06:42:46
Advertisements