Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to remove the first character of string in PHP?
In PHP, you can remove the first character of a string using several methods. The most common approaches are substr() for general use and ltrim() for removing specific characters.
Using substr()
The substr() function is the most straightforward method to remove the first character from any string ?
<?php
$str = "Test";
echo "Before removing the first character = ".$str;
$res = substr($str, 1);
echo "\nAfter removing the first character = ".$res;
?>
This will produce the following output ?
Before removing the first character = Test After removing the first character = est
Using ltrim()
The ltrim() function removes specific characters from the beginning of a string. Use this when you know which character to remove ?
<?php
$str = "Demo";
echo "Before removing the first character = ".$str;
$res = ltrim($str, 'D');
echo "\nAfter removing the first character = ".$res;
?>
This will produce the following output ?
Before removing the first character = Demo After removing the first character = emo
Comparison
| Method | Use Case | Advantage |
|---|---|---|
substr() |
Remove first character regardless of value | Works with any string |
ltrim() |
Remove specific characters from beginning | More selective removal |
Conclusion
Use substr($string, 1) for general first character removal and ltrim() when you need to remove specific characters. Both methods are efficient and widely supported.
Advertisements
