How to Remove the Last Character of a String in PHP

0 min read 87 words

If you need to remove the last character of a string in PHP, then you can do the following:

Option 1 – Using rtrim()

Syntax: rtrim($string, $character)

$mystring = "This is a PHP program!";
echo("Before Removal: $mystring\n");
# Before Removal: This is a PHP program!

$newstring = rtrim($mystring, ". ");
echo("After Removal: $newstring");
# After Removal: This is a PHP program

Option 2 – Using substr()

Syntax: substr($string, $start, $length)

$mystring = "This is a PHP program!";
echo substr($mystring, 0, -1);
# This is a PHP program
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags