2011-01-24 97 views

回答

8

您應該使用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<br/>", $pregtime); 
printf("rtrim: %f<br/>", $trimtime); 

結果

的preg_replace:0.000036
RTRIM:0.000004

正如你所看到的,rtrim實際上是nine times更快。

0

用了preg_replace,你想:

$s = ' okoki efef ef ef 
'; 

print('-'.$s.'-<br/>'); 

$s = preg_replace('/\s+$/m', '', $s); 

print('-'.$s.'-');