Skip to content
Fix Code Error

startsWith() and endsWith() functions in PHP

March 13, 2021 by Code Error
Posted By: Anonymous

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

Solution

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;
}

Use this if you don’t want to use a regex.

Answered By: Anonymous

Related Articles

  • Reference - What does this regex mean?
  • Reference — What does this symbol mean in PHP?
  • easiest way to extract Oracle form xml format data
  • Simple C example of doing an HTTP POST and consuming the…
  • What are the undocumented features and limitations of the…
  • How to format a phone number in a textfield
  • ng if with angular for string contains
  • PHP parse/syntax errors; and how to solve them
  • How to check if a string "StartsWith" another string?
  • problem with client server unix domain stream sockets…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to do case insensitive string comparison?

Next Post:

How can I get form data with JavaScript/jQuery?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error