php rtrim直到特定字符

时间:2011-12-08 10:07:59

标签: php string substr

我想在一个字符串上做一个rtrim直到特定的字符如“”(空格)

输入:“Lorem ipsum dolor sit amet,consectetur adipiscing el”

输出:“Lorem ipsum dolor sit amet,consectetur adipiscing”

尝试了几件事,但他们似乎都反过来......

先谢谢

彼得

3 个答案:

答案 0 :(得分:1)

你尝试过这个吗?

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

答案 1 :(得分:0)

$s =  "Lorem ipsum dolor sit amet, consectetur adipiscing el";
$s = preg_replace('/\s\S+$/i','',$s);
echo $s;

其中\s是您的特殊字符

preg_replace('/^\S+\s/i','',$s); // is for ltrim analog

答案 2 :(得分:0)

或非正则表达式版本:

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