开发者

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜