Appearance
How to Remove the First Character of a String with PHP
In this tutorial, we will show you three main PHP functions used for removing the first character of a string.
Check out the examples and choose the one that suits your project best.
Using ltrim
The first PHP function that you can use for removing the first character of a string is ltrim().
All you need to do is apply the code below:
php
<?php
$str = '::f:o:';
$str = ltrim($str, ':');
var_dump($str); //=> 'f:o:'
?>Using substr
The second recommended approach is using the substr() function. Here is how to use it:
php
<?php
$str = 'hello';
$str = substr($str, 1);
var_dump($str); //=> 'ello'
?>Using preg_replace
And the last handy function to use for removing the first character of a string is preg_replace():
php
<?php
$str = "hello";
$str = preg_replace('/^./', '', $str);
var_dump($str); //=> 'ello'
?>Describing the ltrim Function
The ltrim() function is supported in PHP 4, PHP 5, and PHP 7. It returns a string with whitespace (or specified characters) stripped from the beginning.
Describing the substr Function
The substr() function is a built-in PHP function used for extracting a part of a string.
It is capable of returning the extracted part of a string if successful. On failure, it will return either false or an empty string.
Describing the preg_replace Function
The preg_replace() function can return a string or an array of strings. It replaces all matches of a pattern found in the input string with a replacement string.