13 Votes

PHP: strStart and strEnd functions

Tip by NetGuy | 2014-03-29 at 20:10

When programming in PHP, often, I am missing a simple function to check whether a string is starting or ending with a specific string or character. In other words, something like strStart or strEnd well known from other programming languages.

Of course, you can solve this problem by using substr() or strpos(), but it is much more easier if you have the following functions:

function strStart($s, $search) {
  return substr($s, 0, strlen($search)) === $search; 
}

function strEnd($s, $search) {
  return substr($s, -strlen($search)) === $search;
}

A call of this functions can look like this, for example:

$s = "abcdef";

if (strStart($s, "abc")) {  }  // true
if (strEnd($s, "def"))   {  }  // true

As a first paramater you are passing the string you would like to check, as a second parameter you are passing the search string.

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.