Skip to content
Advertisement

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 ;-

Delux Room_room
Delux Room_
Delux R

But i want Delux Room. Please help me.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement