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,}+/',
精彩评论