Home » Php » Removing first slash character from string PHP

Removing first slash character from string PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have a string of this format /abcd-efg-sms-3-topper-2

I want to remove the first / character from this.

I know I can remove this using substr() function, but I do not want to use that, since I first have to check if first character is the slash. Is there any other way I can remove the slash, without first checking for the slash, and have that way be reasonably performant (i.e. avoiding complex regular expresions)?

How to&Answers:

Use trim:

$string = '/abcd-efg-sms-3-topper-2';
echo ltrim($string, '/');
// abcd-efg-sms-3-topper-2
echo rtrim($string, '/');
// /abcd-efg-sms-3-topper-2
echo trim($string, '/');
// abcd-efg-sms-3-topper-2