rtrim with underscore in php
I have line as 'Delux Room_room'. I want get 'Delux Room' as result. I tried following codes.
Following code give following result.
echo $row.'<br/>';
echo rtrim($row, 'room') .'<br/>';
echo rtrim($row, '_room') .'<br/>';
Result ;-
Del开发者_Python百科ux Room_room
Delux Room_
Delux R
But i want Delux Room. Please help me.
echo rtrim($row, '_room') .'<br/>';
That says "remove characters from the end of the string until you get to one that isn't _
, r
, o
or m
." Which obviously isn't what you mean. From the PHP manual:
$charlist
You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.
You provide a list of characters, not a string you want to remove.
You should probably use substr
instead:
echo substr($row, 0, -5); // remove the last 5 characers
Another solution would be to use str_replace
to replace unwanted substrings:
echo str_replace('_room', '', $row); // replace "_room" with an empty string
Note that this is less precise than the substr
approach.
rtrim
's second argument is a set of characters. You'll have to write your own method to remove a specific string instead:
function rtrim_str($str, $trim) {
if (substr($str, -strlen($trim)) == $trim) {
return substr($str, 0, -strlen($trim));
}
return $str; // String not present at end
}
echo rtrim_str($row, '_room');
Alternatively to @lonesomeday's solution, if your last past is of variable length:
$pos = strrpos($row, '_');
echo $substr($row, 0, $pos);
You should use str_replace
instead of rtrim
, like this:
echo $row.'<br/>';
echo str_replace('room', '', $row) .'<br/>';
echo str_replace('_room', '', $row) .'<br/>';
精彩评论