PHP:PCRE:如何替换可重复的char

Dmi*_*bev 6 php regex pcre preg-replace

例如我有以下字符串:

a_b__c___d____e
Run Code Online (Sandbox Code Playgroud)

如何preg_replace char _到char' - ',但仅当部分'__...'包含多于N重复_时.

我希望你能理解我 ))

source: a_b__c___d____e
cond: change '_' where 2 or more
result: a_b--c---d----e
Run Code Online (Sandbox Code Playgroud)

要么

source: a_b__c___d____e_____f
cont: change '_' where 4 or more
result: a_b__c___d----e-----f
Run Code Online (Sandbox Code Playgroud)

谢谢!

ps有趣的解决方案,不使用循环.如何用循环实现它(我认为)知道任何人.只是一个正则表达式和preg_replace.

Fel*_*ing 2

这是使用修饰符的另一种e

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

替换4为您需要的数字。或者作为函数:

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);
}
Run Code Online (Sandbox Code Playgroud)