2015-04-25 123 views
7

替换多个破折号我有一个字符串,它看起来像这样:一个破折号

something-------another--thing 
     //^^^^^^^  ^^ 

我想用一个单一的一个替换多个破折号。

所以预期输出是:

something-another-thing 
     //^  ^

我试图用str_replace(),但我必须再次编写代码破折号的每一个可能的量。所以,我怎么能有一个替换破折号的任何金额是多少?

对于Rizier:

尝试:

$mystring = "something-------another--thing"; 
str_replace("--", "-", $mystring); 
str_replace("---", "-", $mystring); 
str_replace("----", "-", $mystring); 
str_replace("-----", "-", $mystring); 
str_replace("------", "-", $mystring); 
str_replace("-------", "-", $mystring); 
str_replace("--------", "-", $mystring); 
str_replace("---------", "-", $mystring); 
etc... 

但该字符串可以有两个词之间的线10000。

+1

使用'preg_replace'。 – Barmar

+0

您是否尝试过的东西? – Rizier123

+2

@ Rizier123他说他试过'str_replace' – Barmar

回答

16

使用preg_replace更换模式。

$str = preg_replace('/-+/', '-', $str); 

正则表达式匹配-+ 1个或多个连字符的任何序列。

如果你不理解正则表达式,在www.regular-expression.info阅读教程。

2

可以使用

<?php 
$string="something-------another--thing"; 
echo $str = preg_replace('/-{2,}/','-',$string); 

输出

something-another-thing