2017-03-09 29 views
0

让说,我有这样的如何使用正则表达式替换PHP中的重复标点符号?

Hello ??? WHERE ARE YOU!!!! Comon ?!?!?! 
desired outout 
Hello ? WHERE ARE YOU!!!! Comon ?! 

我怎样才能做到这一点?我试过preg_replace_callback,但没有运气。我使用Finding the shortest repetitive pattern in a string作为起点,但它在完整的句子上工作,我需要它逐字地工作+我需要删除重复的计算(模式)? Live Code

+1

为什么期望的输出不是“你好?你在哪里!科曼?!”? – erisco

+0

@erisco需要清理有哪些文本?!?!?!?!?!?!?!?!?!?!?!?!,!!!!!!!!!!!!!!! ,!!! !!! !!!等 –

回答

0

使用下面的代码:

$str = "Hello ??? WHERE ARE YOU!!!! Comon ?!?!?! ..."; 

$replacement = [ 
    '?', 
    '?!', 
    '.', 
]; 

foreach($replacement as $key => $value){ 
    $pattern[$key] = sprintf("/(\%s)+/", $value); 
} 

echo $outout = preg_replace($pattern, $replacement, $str); 

插入任何标点置换阵列来删除重复的标点符号。

+0

这能改进使用一串标点符号[!!?]并自动找到重复模式吗? –

+1

代码已更新。要删除任何重复标志,请将其添加到替换数组中。 – MahdiY

+0

顺便说一句你可以想出一种方法来找到重复模式本身就像在这[问题](http://stackoverflow.com/questions/28963384/finding-the-shortest-repetitive-pattern-in-a-string )并将其应用于PHP?我试过但失败了。 –

0

更换\?+?!+!(\?!)+?!,等等。

function dedup_punctuation($str) { 
    $targets  = array('/\?+/', '/!+/', '/(\?!)+/'); 
    $replacements = array('?' , '!' , '?!'  ); 
    return preg_replace($targets, $replacements, $str); 
} 
+0

这工作,但有没有办法找到使用反向引用等自动重复模式?为此,我必须分别输入每个用例。 –

相关问题