开发者

Php Regular Expression repeated characters [take max repeat charachers]

开发者 https://www.devze.com 2023-04-13 06:05 出处:网络
I have a string like this: \"ABCCCCCCCCCCCCCDEF开发者_JAVA百科\" i use the code $value=preg_replace(\'/[C]{3,}/\',\"Z\",$value);

I have a string like this:

"ABCCCCCCCCCCCCCDEF开发者_JAVA百科"

i use the code

$value=preg_replace('/[C]{3,}/',"Z",$value);

return this

"ABZZZZCDEF"

How can i get the following result?

"ABZCDEF"


<?php
$a = "ABCCCCCCCCCCCCCDEF";
echo preg_replace('/[C]+/', 'ZC', $a);
?>

Gives

ABZCDEF


I think this is what you're looking for:

$value = preg_replace('/([C]{3})+/', "Z", $value);

...or, "Replace one or more groups of three C's with a Z." The code you posted does not work the way you say it does. I suspect that, as Tim suggested, you're really doing this:

$value = preg_replace('/[C]{3}/', "Z", $value);

Note the absence of the comma (,). This replaces each group of three C's with a Z, where my version replaces all groups of three C's with one Z.

EDIT: ...or, as mario suggested, you're really doing a non-greedy match. In that case, your "regex" string would be '/[C]{3,}?/' or '/[C]{3,}/U'.


Your preg_replace seems to default to ungreedy. In that case you can change the {3,} quantifier with an extra + so it means a minimum of 3 characters:

 = preg_replace('/[C]{3,}+/',
0

精彩评论

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