使用preg_replace删除字符串末尾的多余空间 [英] Remove extra space at the end of string using preg_replace
问题描述
我想用PHP中的preg_replace
替换字符串末尾的多余空格.我正在创建一个庞大的单词数据库,不知何故,最后几个单词得到了额外的空白.
I want to replace the extra space at the end of the string with nothing using preg_replace
in PHP. I was creating a big database of words and somehow a few words got extra white space at the end.
推荐答案
您应使用
速度比较-
Speed Comparison - 结果 preg_replace:0.000036 preg_replace: 0.000036 如您所见, As you can see, 这篇关于使用preg_replace删除字符串末尾的多余空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
preg_replace
v.trim
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);
rtrim:0.000004
rtrim: 0.000004rtrim
实际上是 九次 更快.rtrim
is actually nine times faster.