views:

84

answers:

5

Say I have

sometext-somemore--test---test2

how could I have it replace all instaces where there are more than 1 - and have it replace them with just 1 so it would look like this

sometext-somemore-test-test2

+2  A: 

use a regex: s/-+/-/ The + says 'one or more of the preceding character'.

dnagirl
A: 
Brendan Long
I don't see how the for/if loop would work.. as far as I can see, it replaces '55' with '5' if characters 4 and 5 are both 'x'. You'd want to check that $text[$i] == '-' also, and you'd have to use substr_replace($text, '-', $i, 2) instead of str_replace(). Regex is probably the way to go, though.
MSpreij
@MSpreij: It seems Brendan was trying to create an algorithm to replace arbitrary repeating characters. @Brendan Long: Try this instead: preg_replace('{(.)\1+}', '$1', $text);
webbiedave
Yeah when i read it, I thought the question was asking how to replace any two repeating characters :\
Brendan Long
+5  A: 

Use preg_replace.

preg_replace('/-+/', '-', $mystr);
David
A: 

Use this:

echo preg_replace("/-+/","-","sometext-somemore--test---test2");
//prints sometext-somemore-test-test2
zombat
+1  A: 

You could do this with a regular expression and the preg_replace function :

$str = 'sometext-somemore--test---test2';
echo preg_replace('/-+/', '-', $str);

would give you :

sometext-somemore-test-test2


The pattern I used here : -+

  • Matches a -
  • One or more than one time : +

And don't hesitate to read the PCRE Patterns section of the manual, if you are interested by regular expressions ;-)

Pascal MARTIN