ITChristian
ITChristian

Reputation: 11271

Replace multiple dashes with one dash

I have a string which looks like this:

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

I want to replace the multiple dashes with a single one.

So the expected output would be:

something-another-thing
       //^       ^

I tried to use str_replace(), but I have to write the code again for every possible amount of dashes. So how can I replace any amount of dashes with a single one?

For Rizier:

Tried:

 $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...

But the string could have 10000 of lines between two words.

Upvotes: 15

Views: 10084

Answers (3)

dazzafact
dazzafact

Reputation: 2860

if you have a string with multiple Charakters to clean use this:

$string="Hello,,,my text contains unused characters... What can i do???"
$newString=preg_replace('#([\-\.\?])\\1+#','$1',$string);

if you have a string with unknown multiple signs to clean use this:

$string="!!!!A string with ooooother unknoooooown multiple Signs!!!!"
$newString=preg_replace('#([.])\\1+#','$1',$string);

Upvotes: 2

Saty
Saty

Reputation: 22532

you can use

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

Output

something-another-thing

Upvotes: 7

Barmar
Barmar

Reputation: 781255

Use preg_replace to replace a pattern.

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

The regular expression -+ matches any sequence of 1 or more hyphen characters.

If you don't understand regular expressions, read the tutorial at www.regular-expression.info.

Upvotes: 40

Related Questions