我想在一个字符串上做一个rtrim直到特定的字符如“”(空格)
输入:“Lorem ipsum dolor sit amet,consectetur adipiscing el”
输出:“Lorem ipsum dolor sit amet,consectetur adipiscing”
尝试了几件事,但他们似乎都反过来......
先谢谢
彼得
答案 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);