【发布时间】:2011-04-17 21:29:55
【问题描述】:
我只是想知道如何用 php 替换多个 - 的实例,
比如说我有
test----test---3
我可以做些什么来替换 - 的多个实例,只需 1 个,这样就可以了
test-test-3
谢谢:)
【问题讨论】:
标签: php string replace preg-replace
我只是想知道如何用 php 替换多个 - 的实例,
比如说我有
test----test---3
我可以做些什么来替换 - 的多个实例,只需 1 个,这样就可以了
test-test-3
谢谢:)
【问题讨论】:
标签: php string replace preg-replace
删除每个重复的字符:
$string = 'test----test---3';
echo preg_replace('{(.)\1+}','$1',$string);
删除特定的重复字符:
$string = 'test----test---3';
echo eregi_replace("-{2,}", "-", $string);
以“丑陋”的方式删除特定的重复字符:
$string = 'test----test---3';
echo implode('-',array_filter(explode('-',$string)));
所有 sn-ps 的结果:
test-test-3
【讨论】:
嗯……
function replaceDashes($str){
while(strpos($str,'--')!==false)
$str=str_replace('--','-',$str);
return $str;
}
你可以让它“更快”被替换:
$str=str_replace('--','-',$str);
与:
$str=str_replace(array('----','---','--'),'-',$str);
【讨论】:
由于eregi_replace和ereg_replace在PHP5中已经贬值,你也可以试试
preg_replace("/-{2,}/", "-", $string);
所以如果你运行
preg_replace("/-{2,}/", "-", "--a--b---c----")
它会返回
-a-b-c-
【讨论】: