In this tutorial, you will learn to remove the first 2, 3, 4, 5, 10, characters from string in PHP.
To Remove First Character From String PHP
Let’s use ltrim()
, substr_replace()
or substr()
PHP function to remove first character from the string:
Method 1: substr function
You can use the substr function of PHP for remove the first character from string in PHP.
Here is 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.
Recommended Posts:
To remove specific characters from string PHPMethod 2: ltrim() function
You can use the PHP ltrim() function to remove the first character from the given string in PHP.
Here is 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
Method 3: Using substr_replace() function
The substr_replace() function is used to replace a part of a string with another string:
$string = "Hello World!";
$newString = substr_replace($string, "", 0, 1);
echo $newString; // Output: "ello World!"
Conclusion
In PHP, removing the first character from a string is a simple task that can be accomplished using either the substr() function or the substr_replace() or ltrim() function.