Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 891
Dmitrij Golubev Avatar asked May 17 '11 12:05

Dmitrij Golubev


3 Answers

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);
}
like image 56
Felix Kling Avatar answered Sep 21 '22 10:09

Felix Kling


$source = 'a_b__c___d____e_____f';
function yourfunc($param)
{
    $count  = strlen($param);
    $return = '';
    for ($i = 0; $i < $count; $i++)
    {
        $return .= '-';
    }
    return $return;
}
echo preg_replace('#(_{4,})#e', 'yourfunc("$1");', $source);

A solution without callback function and loop is much harder to read.

preg_replace('#(_{4,})#e', 'implode("", array_pad(array(), strlen("$1"), "-"));', $source);
like image 36
Sebastian Schmidt Avatar answered Sep 22 '22 10:09

Sebastian Schmidt


this is inline solution :

preg_replace('/(_{2,})/ie', 'str_repeat("-",strlen("$1"));', $source);

and reusable funciton:

$source = 'a_b__c___d____e_____f';


    function replace_repeatable($source,$char,$replacement,$minrepeat = 2)
    {
          return preg_replace('/(' . preg_quote($char) . '{' . $minrepeat . ',})/ie', 'str_repeat("' . $replacement . '",strlen("$1"));', $source);
    }

    $b = replace_repeatable($source,'_','-',4);
like image 37
Tufan Barış Yıldırım Avatar answered Sep 24 '22 10:09

Tufan Barış Yıldırım