Skip to content
Prem Tiwari
  • WP Tutorials
  • Plugins
  • About Me
  • Featured On
  • Let’s Talk
Prem Tiwari
Home / PHP / How to Remove the Last Character from a String in PHP

How to Remove the Last Character from a String in PHP

ByPrem Tiwari Last updated onDecember 9, 2024

In this post, I will share the best way to remove the last character from a string in PHP, you can use one of the following methods. All the methods mentioned belows are tried and tested with latest PHP 8.x version.

Method 1: Using substr()

The substr() function allows you to extract a part of a string. To remove the last character, specify the start and length of the substring you want to keep.

<?php
$string = "Hello, World!";
$result = substr($string, 0, -1); // Removes the last character
echo $result; // Output: Hello, World
?>

Method 2: Using rtrim()

If the last character is whitespace or a specific character, you can use rtrim().

<?php
$string = "Hello, World!";
$result = rtrim($string, "!"); // Removes the "!" at the end
echo $result; // Output: Hello, World
?>

Method 3: Using preg_replace()

For pattern-based removal, preg_replace() can be used.

<?php
$string = "Hello, World!";
$result = preg_replace('/.$/', '', $string); // Removes the last character
echo $result; // Output: Hello, World
?>

Let me know if you have any questions in the comment section below! 😊

Found it helpful? Share it with your friends on social media!

  • Facebook
  • Post on X
  • LinkedIn
Prem Tiwari

Prem Tiwari is a passionate advocate of open source technology, with over 10+ years of experience in the WordPress domain. He has great experience when it comes to scaled WordPress projects which caters the need for big enterprise clients on WordPress and WordPress VIP-GO platform.

Facebook Twitter Instagram YouTube Linkedin

Post navigation

Previous Previous
How to Secure Your WordPress Site in 4 Simple Steps
NextContinue
WordPress Plugin Development: From Idea to Marketplace

Collections

  • Crawling and indexing
  • Meetup
  • PHP
  • Plugins
  • SEO
  • Tech Talks
  • WooCommerce Tutorials
  • WordCamp
  • WordPress Tutorials
  • Privacy
  • Cookies
  • Disable Update Notifications
Facebook Twitter Instagram YouTube Linkedin WordPress
Scroll to top
  • WP Tutorials
  • Plugins
  • About Me
  • Featured On
  • Let’s Talk