How do i replace two-or-more occurences of the same char with another char?
I'm trying to come up with a piece of PHP code that replaces multiple adjacent occurences of a char in a string with only one occurence of that char.
Example:
my-string--is---dashed
开发者_如何学运维should become:
my-string-is-dashed
The most straightforward solution would be to use a regular expression replace.
$output = preg_replace('/-+/', '-', $input);
In reality, to limit the vacuous replaces, you might elect to go with the following:
$output = preg_replace('/-{2,}/', '-', $input);
With a regexp :
var_dump(preg_replace('/-{2,}/', '-', 'my-string--is---dashed')); // string(19) "my-string-is-dashed"
If you meant any repeating character, it's a bit more complicated :
var_dump(preg_replace('/(.)(\\1)+/', '$1', 'tttooosssdihfjkkk')); string(9) "tosdihfjk"
Where \\1
is basically matched character (matched by (.)
).
Try this:
$new_string = preg_replace('/-{2,}/', '-', $string);
str_replace("--", "-", $mystring);
精彩评论