How to Remove the Last Character from a String in PHP

PHOTO EMBED

Sun May 18 2025 06:36:03 GMT+0000 (Coordinated Universal Time)

Saved by @Samuel88 #php

<?php 

// A message stored in a string
$statusMessage = "Process completed#";

// Remove the last symbol from the message
$cleanMessage = substr($statusMessage, 0, -1);

// Display the messages
echo "Before cleanup: " . $statusMessage . "\n";
echo "After cleanup: " . $cleanMessage . "\n";


// Here is the output

/*
Before cleanup: Process completed#
After cleanup: Process completed
*/
content_copyCOPY

This PHP snippet defines a string $statusMessage with the value "Process completed#" and removes the last character (the # symbol) using the substr() function. The call substr($statusMessage, 0, -1) returns a new string starting from the first character up to—but not including—the last one. This result is stored in $cleanMessage. Finally, it prints both the original and the cleaned strings. The output shows the message before cleanup as "Process completed#" and after cleanup as "Process completed".

https://flatcoding.com/tutorials/php/php-remove-last-character-from-string/