PHP remove first character from a string

To remove the first character from a string, you can use the ltrim() or substr() function.

The ltrim() function is used to strip whitespace from the beginning of a string.

To use the function, you need to pass the string and the character(s) to remove.

Consider the example below:

<?php
$str = "-Hello World!";
// πŸ‘‡ remove the dash in front of H
$new_string = ltrim($str, "-");

print $new_string; // Hello World!
?>

But keep in mind that the ltrim() function removes all occurrences of the character(s) you specified as its second parameter:

<?php
$str = "---Hello World!";
// πŸ‘‡ remove dashes in front of H
$new_string = ltrim($str, "-");

print $new_string; // Hello World!

If you explicitly want to remove only the first character, you need to use the substr() function instead.

The substr() function is used to return a portion of a string. You can use it to cut the first character as shown below:

<?php
$str = "---Hello World!";
// πŸ‘‡ remove the first dash in front of H
$new_string = substr($str, 1);

print $new_string; // --Hello World!
?>

The second parameter of the substr() function determines the offset position where the function begins to cut the string.

Because a string index starts from 0, passing 1 as the offset position will cause the function to remove the first character from the string.

And that’s how you remove the first character in PHP. Nice! πŸ‘

Take your skills to the next level ⚑️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.