Home  »  CodeLibrariesProgrammingSnippetsTechnology   »   How to Remove the Last Character from a String in PHP

How to Remove the Last Character from a String in PHP

Posted: January 25, 2023 | by Michael Bright

Remove the last character from a string in PHP using the substr function.

<?php
  $string = "Hello World!";
  $updatedstring = substr($string, 0, -1);
  echo $updatedstring;
?>

The output will display this:

Hello World

Using the substr_replace function.

<?php
  $string = "Hello World!";
  $updatedstring = substr_replace($string, "", -1);
  echo $updatedstring;
?>

The output will display this:

Hello World

Using the rtrim function to remove a particular character.

<?php
  $string = "Hello Worldy";
  $updatedstring = rtrim($string, 'y');
  echo $updatedstring;
?>

The output will display this:

Hello World

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.