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.
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);
}
$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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With