Remove First 2, 3, 4, 5, 10, etc, Character From String PHP

When you work with PHP, Many time, you want to you remove first, last and middle characters from strings. This tutorial shows you various PHP functions for removing the first character from the given string.

This tutorial shows you a simple and easy method for delete or remove first 1, 2, 3, 4, 5, 10, etc., characters from string in PHP.

To Remove First Character From String PHP

This tutorial demonstrates an easy way for you. To remove the first character from string in PHP.

1.Method First – substr function

You can use the substr function of PHP for remove the first character from string in PHP.

Syntax:

The syntax of subster method is given below:

substr($string);

Example1 – Method First – substr function

 $string = "Hello World!";
 echo "Given string: " . $string . "\n";
 echo "Updated string: " . substr($string, 1) . "\n";

 

Output-1

 Given string: Hello World!
 Updated string: ello World

Example2 – PHP substr function

Suppose you have one string like this “Hi, You are a good programmer.” . In this string you want to remove first three characters in PHP. So you can use the substr() function like this:

$string = "Hi, You are a good programmer.";
echo "Given string: " . $string . "\n";
echo "Updated string: " . substr($string, 3) . "\n"; 

Using the above example2 of method substr, you can remove first n number of characters from string in PHP.

Output-2

Given string: Hi, You are a good programmer.
Updated string: You are a good programmer.

2. Method Two – ltrim() function

You can use the PHP ltrim() function to remove the first character from the given string in PHP.

Syntax:

The basic syntax of ltrim() function is:

ltrim($string,'h');

Here “h” is the character that you want to remove in your string.

Example – ltrim() function

$string = "Hello World!";
 echo "Given string: " . $string . "\n";
 echo "Updated string: " . ltrim($string, "!") . "\n";

Output

 Given string: Hello World!
 Updated string: ello World 

Conclusion

PHP Remove the first character from a string. In this tutorial, you have many methods of PHP to remove the first character from any given strings.

Leave a Reply

Your email address will not be published. Required fields are marked *