Search code examples
phpregexpreg-replacepcre

PHP:PCRE: How to replace repeatable char


for example I have following string:

a_b__c___d____e

How to preg_replace char _ to char '-', but only if part ' __...' contains more than N repeated _.

I hope you understand me ))

source: a_b__c___d____e
cond: change '_' where 2 or more
result: a_b--c---d----e

or

source: a_b__c___d____e_____f
cont: change '_' where 4 or more
result: a_b__c___d----e-----f

Thanks!

p.s. Interesting solution without using loops. How implement it with loops (I think) know anybody. Just a one regex and preg_replace.


Solution

  • Here is another one using the e modifier:

     $str = 'a_b__c___d____e_____f';
     echo preg_replace('/_{4,}/e', 'str_repeat("-", strlen("$0"))', $str);
    

    Replace 4 by the number you need. Or as function:

    function repl($str, $char, $times) {
        $char = preg_quote($char, '/');
        $times = preg_quote($times, '/');
        $pattern = '/' . $char . '{' . $times . ',}/e',
        return preg_replace($pattern, 'str_repeat("-", strlen("$0"))', $str);
    }