PHP 8.3.0 RC 6 available for testing

rtrim

(PHP 4, PHP 5, PHP 7, PHP 8)

rtrim删除字符串末端的空白字符(或者其他字符)

说明

rtrim(string $string, string $characters = " \n\r\t\v\x00"): string

该函数删除 string 末端的空白字符(或者其他字符)并返回。

不使用第二个参数,rtrim() 仅删除以下字符:

  • " " (ASCII 32 (0x20)),普通空白符。
  • "\t" (ASCII 9 (0x09)),制表符。
  • "\n" (ASCII 10 (0x0A)),换行符。
  • "\r" (ASCII 13 (0x0D)),回车符。
  • "\0" (ASCII 0 (0x00)),NUL 空字节符。
  • "\v" (ASCII 11 (0x0B)),垂直制表符。

参数

string

输入字符串。

characters

通过指定 characters,可以指定想要删除的字符列表。简单地列出你想要删除的全部字符。使用 .. 格式,可以指定一个范围。

返回值

返回改变后的字符串。

示例

示例 #1 rtrim() 使用示例

<?php

$text
= "\t\tThese are a few words :) ... ";
$binary = "\x09Example string\x0A";
$hello = "Hello World";
var_dump($text, $binary, $hello);

print
"\n";

$trimmed = rtrim($text);
var_dump($trimmed);

$trimmed = rtrim($text, " \t.");
var_dump($trimmed);

$trimmed = rtrim($hello, "Hdle");
var_dump($trimmed);

// 删除 $binary 末端的 ASCII 码控制字符
// (包括 0 - 31)
$clean = rtrim($binary, "\x00..\x1F");
var_dump($clean);

?>

以上示例会输出:

 
string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(30) "        These are a few words :) ..."
string(26) "        These are a few words :)"
string(9) "Hello Wor"
string(15) "    Example string"

参见

  • trim() - 去除字符串首尾处的空白字符(或者其他字符)
  • ltrim() - 删除字符串开头的空白字符(或其他字符)

add a note

User Contributed Notes 14 notes

up
39
pinkgothic at gmail dot com
13 years ago
I have an obsessive love for php's array functions given how extremely easy they've made complex string handling for me in various situations... so, have another string-rtrim() variant:

<?php

function strrtrim($message, $strip) {
// break message apart by strip string
$lines = explode($strip, $message);
$last = '';
// pop off empty strings at the end
do {
$last = array_pop($lines);
} while (empty(
$last) && (count($lines)));
// re-assemble what remains
return implode($strip, array_merge($lines, array($last)));
}

?>

Astonishingly, something I didn't expect, but: It completely compares to harmor's rstrtrim below, execution time wise. o_o Whee!
up
27
gbelanger at exosecurity dot com
17 years ago
True, the Perl chomp() will only trim newline characters. There is, however, the Perl chop() function which is pretty much identical to the PHP rtrim()

---

Here's a quick way to recursively trim every element of an array, useful after the file() function :

<?php
# Reads /etc/passwd file an trims newlines on each entry
$aFileContent = file("/etc/passwd");
foreach (
$aFileContent as $sKey => $sValue) {
$aFileContent[$sKey] = rtrim($sValue);
}

print_r($aFileContent);
?>
up
24
todd at magnifisites dot com
20 years ago
This shows how rtrim works when using the optional charlist parameter:
rtrim reads a character, one at a time, from the optional charlist parameter and compares it to the end of the str string. If the characters match, it trims it off and starts over again, looking at the "new" last character in the str string and compares it to the first character in the charlist again. If the characters do not match, it moves to the next character in the charlist parameter comparing once again. It continues until the charlist parameter has been completely processed, one at a time, and the str string no longer contains any matches. The newly "rtrimmed" string is returned.
<?php
// Example 1:
rtrim('This is a short short sentence', 'short sentence');
// returns 'This is a'
// If you were expecting the result to be 'This is a short ',
// then you're wrong; the exact string, 'short sentence',
// isn't matched. Remember, character-by-character comparison!
// Example 2:
rtrim('This is a short short sentence', 'cents');
// returns 'This is a short short '
?>
up
20
Unimagined at UnaimaginedDesigns dot Com
18 years ago
I needed a way to trim all white space and then a few chosen strings from the end of a string. So I wrote this class to reuse when stuff needs to be trimmed.

<?php

class cleaner {

function
cleaner ($cuts,$pinfo) {
$ucut = "0";
$lcut = "0";
while (
$cuts[$ucut]) {
$lcut++;
$ucut++;
}
$lcut = $lcut - 1;
$ucut = "0";
$rcut = "0";
$wiy = "start";

while (
$wiy) {

if (
$so) {
$ucut = "0";
$rcut = "0";
unset(
$so);
}

if (!
$cuts[$ucut]) {
$so = "restart";
} else {
$pinfo = rtrim($pinfo);
$bpinfol = strlen($pinfo);
$tcut = $cuts[$ucut];
$pinfo = rtrim($pinfo,"$tcut");
$pinfol = strlen($pinfo);

if (
$bpinfol == $pinfol) {
$rcut++;
if (
$rcut == $lcut) {
unset(
$wiy);
}
$ucut++;
} else {
$so = "restart";
}
}
}

$this->cleaner = $pinfo;
}

}

$pinfo = "Well... I'm really bored...<br /><br>&nbsp; \n\t&nbsp;<br><br /><br>&nbsp; \r\r&nbsp;<br>\r<br /><br>\r&nbsp; &nbsp;\n<br> <br />\t";

$cuts = array('\n','\r','\t',' ',' ','&nbsp;','<br />','<br>','<br/>');

$pinfo = new cleaner($cuts,$pinfo);
$pinfo = $pinfo->cleaner;

print
$pinfo;

?>

That class will take any string that you put in the $cust array and remove it from the end of the $pinfo string. It's useful for cleaning up comments, articles, or mail that users post to your site, making it so there's no extra blank space or blank lines.
up
13
pinkgothic at gmail dot com
10 years ago
On the recurring subject of string-stripping instead of character-stripping rtrim() implementations... the simplest (with a caveat) is probably the basename() function. It has a second parameter that functions as a right-trim using whole strings:

<?php

echo basename('MooFoo', 'Foo');

?>

...outputs 'Moo'.

Since it also strips anything that looks like a directory, it's not quite identical with hacking a string off the end:

<?php

echo basename('Zoo/MooFoo', 'Foo');

?>

...still outputs 'Moo'.

But sometimes it gets the job done.
up
3
harmor
15 years ago
I'm sure there's a better way to strip strings from the end of strings.

<?php
/**
* Strip a string from the end of a string
*
* @param string $str the input string
* @param string $remove OPTIONAL string to remove
*
* @return string the modified string
*/
function rstrtrim($str, $remove=null)
{
$str = (string)$str;
$remove = (string)$remove;

if(empty(
$remove))
{
return
rtrim($str);
}

$len = strlen($remove);
$offset = strlen($str)-$len;
while(
$offset > 0 && $offset == strpos($str, $remove, $offset))
{
$str = substr($str, 0, $offset);
$offset = strlen($str)-$len;
}

return
rtrim($str);

}
//End of function rstrtrim($str, $remove=null)

echo rstrtrim('Hello World!!!', '!') .'<br />'; //"Hello World"
echo rstrtrim('Hello World!!!', '!!') .'<br />'; //"Hello World!"
echo rstrtrim('Hello World!!!', '!!!') .'<br />'; //"Hello World"
echo rstrtrim('Hello World!!!', '!!!!').'<br />'; //"Hello World!!!"
?>
up
-3
HW
20 years ago
<?php
$text
= "This string contains some unwanted characters on the end.";
$text1 = rtrim($text, 'a..z');
$text1 = rtrim($text1, '.');
echo
$text1; // only the '.' is trimmed.
$text2 = rtrim($text, 'a..z.');
echo
$text2; // The whole last word is trimmed.
?>
up
-7
krzysiek dot 333 at gmail dot com
11 years ago
function read_more($in,$len=160){
if(strlen($in)>$len){
return preg_replace('/[\s\.,][^\s\.,]*$/u', '', substr($in, 0, $len)).'...';
}else{
return $in;
}
}

echo read_mode("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Proin nibh augue, suscipit a, scelerisque sed, lacinia in, mi. Cras vel lorem. Etiam pellentesque aliquet tellus. Phasellus pharetra nulla ac diam. Quisque semper justo at risus. Donec venenatis, turpis vel hendrerit interdum, dui ligula ultricies purus, sed posuere libero dui id orci.");
/* Output:
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Proin nibh augue, suscipit a, scelerisque sed, lacinia in, mi. Cras vel lorem. Etiam pellentesque...*/
up
-15
YAS
17 years ago
To remove an unwanted character - example "." - if exist or not.

The example above doesn't include the case where there is no "."
If there is not "." at the example above the last word will be deleted.

Have fun with this code.

<?php
$text
= "This string contains. some unwanted characters on the end .";
$text = trim($text);
$last = $text{strlen($text)-1};
if (!
strcmp($last,"."))
{
$text = rtrim($text, 'a..z');
$text = rtrim($text, '.');
}
?>
up
-11
andreipop2005 at gmail dot com
8 years ago
Trim limit would be really helpfull. I made a little helper function to do a rtrim with a limited number of replaces:

<?php
function rtrim_limit($str, $delim, $count = 0)
{
if (
$count == 0) return rtrim($str, $delim);

$l = strlen($delim);
$k = 0;

while (
substr($str, -$l) == $delim && ($count == 0 || ($count > 0 && $k++ < $count))) {
$str = substr($str, 0, strlen($str) - $l);
}

return
$str;
}
?>
up
-16
Anonymous
9 years ago
To ltrim or rtrim a dot it have to be escaped ltrim('.1252', '\.')
up
-28
NBS Studio
13 years ago
The simplest way to strip a newline form a text file is ltrim();

trim or explode or split ("\n" or "\r\n") doesn't work in all cases, so give ltrim(); a try instead.
up
-29
info at nbs-studio dot com
13 years ago
The simplest way to strip a newline form a text file is ltrim();

trim or explode or split ("\n" or "\r\n") doesn't work in all cases, so give ltrim(); a try instead.
up
-36
pLIMP
11 years ago
Function similar to rtrim only this will truncate the string at the 1st occurence of any character from $charlist

<?php

function rstrip($string, $charlist = "\t ") {
// removes everything from first occurence of char in charlist to end of string

$charlist = str_split($charlist);
$pos = strlen($string);

foreach (
$charlist as $char) {
$pos = min(strpos($string, $char), $pos);
}

$string_stripped = substr($string, 0, $pos);

return
$string_stripped;
}

?>
To Top