2011-05-17 28 views
6

,比如我有以下字符串:PHP:PCRE:如何替换重复字符

a_b__c___d____e 

如何的preg_replace焦炭_为char ' - ',但只有部分 '__...' 包含超过N重复_。

我希望你能理解我))

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

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

谢谢!

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

回答

2

这里是另外一个使用e修改:

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

由你所需要的数量更换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); 
} 
1
$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); 

没有回调函数和循环的解决方案很难阅读。

preg_replace('#(_{4,})#e', 'implode("", array_pad(array(), strlen("$1"), "-"));', $source); 
1

这是在线解决方案:

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

和可重复使用的功能可按:

$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); 
0

为指php.net使用修改edocumenation气馁,

此功能有从PHP 5.5.0开始已经被取消。依靠这个功能是非常不鼓励的。

所以我们最好不使用这个修饰符来实现我们的目标。


这里的基础上的解决方案是最新的PHP的工具:

$source = 'a_b__c___d____e'; 

echo preg_replace_callback("%(_{2,})%i", function($matches) {return str_repeat("-", strlen($matches[1])); }, $source); 
/* in callback function matches[0] is whole matched pattern, groups go like this matches[1],matches[2]... */ 

即使e在我们的PHP环境仍然可用,所以一般最好使用回调函数 - 感谢的回调,我们避免而不是不安全的addslashes()函数和字符串评估组合,因为使用提到的修饰符运行preg_replace一次涉及两个操作。


一个preg_replace_callback已自4.0.5版本,但function($matches) {}是运行这段代码u需要在版本的PHP匿名函数,它实际上是非常新的语言功能,5.3.0或更高版本