Currently Browsing: Home » Delete the First Character of a String with PHP

Delete the First Character of a String with PHP

When it comes to any skill, reinforcing the basics can pave the way for a boundless future. Indeed, taking a step back and presenting simple topics promotes a better form of comprehension. Thus, today’s post focuses on one primordial PHP function: how to delete the first character of a string.

To accomplish this task, you should be familiar with PHP’s substr( $string, $start, [ $length ] ) function. When used with only the first two parameters, substr returns all characters in $string from index $start to strlen( $string ) - 1 (the end), inclusive. Note that the first index of a string is actually zero.

With this baseline knowledge, writing a function to delete the first character of a string becomes quite trivial. By passing in a value of one to the substr function, the returned string will contain all characters except the first. Through this acknowledgment, a new PHP function may be created:

function deleteFirstChar( $string ) {
	return substr( $string, 1 );
}

With the above function, you can delete the first character of any string by simply passing it as a parameter:

$newString = deleteFirstChar( $oldString );

If you are having trouble with any other PHP topics, make sure you take full advantage of the documentation.

Tags:

This entry was posted on Sunday, September 6th, 2009 at 05:00:50. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

Want to be notified when someone replies? Subscribe to this post's comment RSS feed.
Any field marked with a * is required.