本文介绍了使用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.
推荐答案
您应使用 rtrim
.它将删除字符串末尾的多余空格,并且比使用preg_replace
更快.
$str = "This is a string. ";
echo rtrim($str);
速度比较-preg_replace
v.trim
Speed Comparison - 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
实际上是 九次 更快.
As you can see, rtrim
is actually nine times faster.
这篇关于使用preg_replace删除字符串末尾的多余空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!