Reputation: 1111
I would like to do a sort of a rtrim on a string until a specific character like a " " (space)
input: "Lorem ipsum dolor sit amet, consectetur adipiscing el"
output: "Lorem ipsum dolor sit amet, consectetur adipiscing"
Tried several things but they all seem to work the other way around...
Thanks in Advance
Peter
Upvotes: 0
Views: 1519
Reputation: 351
Or a non regexp version:
function rTrimToChar($str,$char=" ") {
return (strstr($str,$char)) ? substr($str,0,strrpos($str,$char)) : $str;
}
$str = "Lorem ipsum dolor sit amet, consectetur adipiscing el";
echo rTrimToChar($str);
Upvotes: 0
Reputation: 16951
Did you try this?
$string = 'Lorem ipsum dolor sit amet, consectetur adipiscing el';
$strlen = strlen($string);
$length = strrpos($string, ' ');
if ($length === FALSE) {
$length = $strlen;
}
$result = substr($string, 0, $length);
Upvotes: 1
Reputation: 8079
$s = "Lorem ipsum dolor sit amet, consectetur adipiscing el";
$s = preg_replace('/\s\S+$/i','',$s);
echo $s;
where \s
is your special char
preg_replace('/^\S+\s/i','',$s); // is for ltrim analog
Upvotes: 0