views:

119

answers:

2

Possible Duplicate:
PHP Preg-Replace more than one underscore

Hi, I'm just wondering how I can replace 2 or more - signs in a string with just one in PHP.

So like

1-2---3--4

would go to

1-2-3-4

Thanks :)

+5  A: 

Use preg_replace:

$str = preg_replace('/-+/', '-', $str);
Tatu Ulmanen
or better `$str = preg_replace('/-{2,}/', '-', $str);`
Raveren
@Reveren Wouldn't that miss the --- in the middle of the string?
Neil Aitken
Well, technically that would recude the number of replacements but IMHO the difference is negligible and `/-+/` is a lot cleaner :)
Tatu Ulmanen
@Neil Aitken, no, `{2,}` means 'at least two characters'.
Tatu Ulmanen
@Tatu: it really isn't
SilentGhost
@Tatu ah, I didn't see the ,
Neil Aitken
A: 

No need regex

$text="1-2---3--4";
$s = implode("-",array_filter ( explode("-",$text) )) ;
print_r($s);
ghostdog74
Exploding to array then joining back to string is neither more clear nor effective than the RegEx version.
KennyTM
if that's what you think. But not me.
ghostdog74