W3docs

How to Remove the First Character of a String with PHP

In this short tutorial, we are going to represent to you the three main PHP functions that are used for removing the first character of a string.

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 <kbd class="highlighted">ltrim()</kbd>.

All you need to do is apply the code below:

<?php

$str = '::f:o:';
$str = ltrim($str, ':');
var_dump($str); //=> 'f:o:'

?>

Using substr

The second recommended approach is using the <kbd class="highlighted">substr()</kbd> function. Here is how to use it:

<?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 <kbd class="highlighted">preg_replace()</kbd>:

<?php

$str = "hello";
$str = preg_replace('/^./', '', $str);
var_dump($str); //=> 'ello'

?>

Describing the ltrim Function

The <kbd class="highlighted">ltrim()</kbd> 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 <kbd class="highlighted">substr()</kbd> 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 <kbd class="highlighted">preg_replace()</kbd> 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.