简体   繁体   English

如何使用正则表达式替换PHP中的重复标点符号?

[英]How to replace repetitive punctuation in PHP using regex?

Let say, I have this 可以说,我有这个

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

How can I achieve this? 我该如何实现? I tried preg_replace_callback but to no luck. 我尝试了preg_replace_callback但是没有运气。 I used Finding the shortest repetitive pattern in a string as an starting point but it works on complete sentence, I need it to work on word by word + I need to remove duplicate computations only (patterns)? 我以查找字符串中最短的重复模式作为起点,但它适用于完整的句子,我需要它逐字处理+我只需要删除重复的计算(模式)? Live Code 现场代码

Replace \\?+ with ? \\?+替换为? , !+ with ! !+! , (\\?!)+ with ?! (\\?!)+?! , and so on. , 等等。

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

Use below code: 使用以下代码:

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

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

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

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

Insert any punctuation to replacement array to delete repetitive punctuation. 将所有标点插入替换数组以删除重复的标点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM