Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

startsWith() and endsWith() functions in PHP

Tags:

string

php

How can I write two functions that would take a string and return if it starts with the specified character/string or ends with it?

For example:

$str = '|apples}';  echo startsWith($str, '|'); //Returns true echo endsWith($str, '}'); //Returns true 
like image 307
Ali Avatar asked May 07 '09 12:05

Ali


People also ask

What does startsWith function do?

STARTSWITH is a string manipulation function that manipulates all string data types (BIT, BLOB, and CHARACTER), and returns a Boolean value to indicate whether one string begins with another.

How do you check if a string ends with a substring in PHP?

To check if string ends with specific substring, use strcmp() function to compare the given substring and the string from a specific position of the string. Take string in variable $string. Take substring in $substring. Compute the length of $substring and store it in $length.

How do you check if a string starts with PHP?

Just use substr( $string, 0, strlen($query) ) === $query. Per the str_starts_with RFC, the most CPU and memory efficient way to generically check if a string starts with another string prior to PHP 8 is strncmp($haystack, $needle, strlen($needle)) === 0 .

What is the return type of startsWith ()?

Returns: A boolean value: true - if the string starts with the specified character(s) false - if the string does not start with the specified character(s)


2 Answers

PHP 8.0 and higher

Since PHP 8.0 you can use the

str_starts_with Manual and

str_ends_with Manual

Example

echo str_starts_with($str, '|');

PHP before 8.0

function startsWith( $haystack, $needle ) {      $length = strlen( $needle );      return substr( $haystack, 0, $length ) === $needle; } 
function endsWith( $haystack, $needle ) {     $length = strlen( $needle );     if( !$length ) {         return true;     }     return substr( $haystack, -$length ) === $needle; } 
like image 118
MrHus Avatar answered Oct 04 '22 17:10

MrHus


You can use substr_compare function to check start-with and ends-with:

function startsWith($haystack, $needle) {     return substr_compare($haystack, $needle, 0, strlen($needle)) === 0; } function endsWith($haystack, $needle) {     return substr_compare($haystack, $needle, -strlen($needle)) === 0; } 

This should be one of the fastest solutions on PHP 7 (benchmark script). Tested against 8KB haystacks, various length needles and full, partial and no match cases. strncmp is a touch faster for starts-with but it cannot check ends-with.

like image 35
Salman A Avatar answered Oct 04 '22 18:10

Salman A