Sephen
Sephen

Reputation: 1111

php rtrim until specific character

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

Answers (3)

mj7
mj7

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

ioseb
ioseb

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

k102
k102

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

Related Questions