你应该使用
rtrim.它将删除字符串末尾的额外空格,并且比使用preg_replace更快.
$str = "This is a string. ";
echo rtrim($str);
速度比较 – preg_replace v.trim
// Our string
$test = 'TestString ';
// Test preg_replace
$startpreg = microtime(true);
$preg = preg_replace("/^\s+|\s+$/", "", $test);
$endpreg = microtime(true);
// Test trim
$starttrim = microtime(true);
$trim = rtrim($test);
$endtrim = microtime(true);
// Calculate times
$pregtime = $endpreg - $startpreg;
$trimtime = $endtrim - $starttrim;
// Display results
printf("preg_replace: %f
", $pregtime);
printf("rtrim: %f
", $trimtime);
结果
preg_replace: 0.000036
rtrim: 0.000004
如你所见,rtrim实际上更快了nine times.