Showing posts with label PHP rtrim. Show all posts
Showing posts with label PHP rtrim. Show all posts

Wednesday, 3 June 2015

Remove Last Character from String in PHP

This is a very common PHP question of HOW TO remove last character from string in PHP. Find below some ways how to delete last character from string in PHP.
    <?php 
    // method 1 - substr and mb_substr
    substr($string, 0, -1);
    mb_substr($string, 0, -1);
     
    // method 2 - substr_replace
    substr_replace($string, '', -1);
     
    // method 3 - rtrim
    // it trims all specified characters from end of the string
    rtrim($string, ".");
    ?>

Monday, 29 September 2014

rtrim in PHP

PHP rtrim() function is used to stripe white spaces or other predefined characters from the right side of the string.

Syntax:

rtrim(string,charlist)
string : Required. Defines the input string

charlist : Optional. Indicates which character to remove.

If not then  all of the following characters will be removed:

"\0" – NULL
"\t" – tab
"\n" – new line
"\x0B" – vertical tab
"\r" – carriage return
" " – ordinary white space
Example:

<?php
$str_name = "Today is Monday.\n\n";
echo "Without rtrim : ". $str_name;
echo "<br />";
echo "With rtrim : ". rtrim($str_name);
?>
Output will be:
Without rtrim : Today is Monday.
With rtrim : Today is Monday.
If You Select "View Source" in the browser window, you will see the following HTML :

<html>
<body>
Without rtrim : Today is Monday.

<br />With rtrim : Today is Monday
</body>
</html>