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-somemor开发者_运维问答e-test-test2
Use preg_replace.
preg_replace('/-+/', '-', $mystr);
use a regex: s/-+/-/
The + says 'one or more of the preceding character'.
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 :
+
- See Repetition in the PCRE manual, about this.
And don't hesitate to read the PCRE Patterns section of the manual, if you are interested by regular expressions ;-)
Use this:
echo preg_replace("/-+/","-","sometext-somemore--test---test2");
//prints sometext-somemore-test-test2
for($i=0; $i < strlen($text) - 1; $i++){
if($text[$i] == $text[$i+1]){
$text = str_replace($i.$i, $i, $text);
}
}
Nowhere near as efficient as using str_replace() by itself for each character you think might be duplicated, but it will work..
If all you want is to replace two dashes with one:
$text = str_replace("--", "-", $text);
精彩评论