我想使用PHP中的preg_replace将字符串末尾多余的空格替换为空。我正在创建一个庞大的单词数据库,不知何故,有几个单词在最后得到了额外的空白。
发布于 2011-01-25 05:13:56
您应该改用rtrim。它将删除字符串末尾的多余空格,并且比使用preg_replace更快。
$str = "This is a string. ";
echo rtrim($str);preg_replace trim vs.vs.速度比较
// 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实际上是更快的。
发布于 2011-01-25 05:13:43
为什么不直接使用trim() http://php.net/manual/en/function.trim.php
发布于 2011-01-25 05:21:17
使用您想要的preg_replace:
$s = ' okoki efef ef ef
';
print('-'.$s.'-<br/>');
$s = preg_replace('/\s+$/m', '', $s);
print('-'.$s.'-');https://stackoverflow.com/questions/4787219
复制相似问题