How to Remove the Last Character from a String in PHP
Table of Contents
Being familiar with strings in PHP is a must because it is almost exclusively used in web development.
A useful thing to know how to do is remove the last character from a string.
In this post, we'll learn all the different ways to remove the last character from a string in PHP.
Using the substr_replace function
The easiest way to remove the last character from a string is to use the substr_replace
function.
This function takes your string, the replacement string, and the start position of the replacement.
We can take advantage of this by setting the start position to -1
and replace it with an empty string.
PHP$string = 'Hello World!';
$string = substr_replace($string, '', -1);
echo $string;
BASHHello World
Using the substr function
Another way to accomplish this is to use the substr
function.
This function takes your string, the start position, and the length of the substring.
We can pass the length as -1
which essentially removes the last character:
PHP$string = 'Hello World!';
$string = substr($string, 0, -1);
echo $string;
BASHHello World
Conclusion
In this post, we learned how to remove the last character from a string in PHP.
We can either use the substr_replace
function or the substr
function to do this.
Thanks for reading!
- Managing PHP Dependencies with Composer
- Create an RSS Reader in Node
- Getting Started with Electron
- Best Visual Studio Code Extensions for 2022
- How to deploy a Deno app using Docker
- How to deploy an Express app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Using Axios to Pull Data from a REST API