使用preg_replace删除字符串末尾的多余空间 [英] Remove extra space at the end of string using preg_replace

查看:99
本文介绍了使用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.

推荐答案

您应使用


速度比较-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);

结果

preg_replace:0.000036
rtrim:0.000004

preg_replace: 0.000036
rtrim: 0.000004

如您所见,rtrim实际上是 九次 更快.

As you can see, rtrim is actually nine times faster.

这篇关于使用preg_replace删除字符串末尾的多余空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆