2011-01-24 7 views

答えて

3
+0

を私はそれについて考える理由のdidnt。どちらもありがとうございます – daron

+0

@Matthew実際には、それは間違っています。 'trim'は' preg_replace'より速い傾向があります。一般的な経験則として、RegExを使う前に組み込みのPHP関数を使うべきです。 –

+0

@MichaelIrigoyenはい申し訳ありません私の悪い私は彼らに何らかの理由で間違った方法ラウンドを得た! http://maettig.com/code/php/php-performance-benchmarks.php – Matthew

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です。 preg_replaceと

0

あなたが望んでいたとして:

$s = ' okoki efef ef ef 
'; 

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

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

print('-'.$s.'-'); 
関連する問題