简体   繁体   English

PHP Regex将重复的字符减少为单个实例

[英]PHP Regex reduce a repeated character to a single instance

I want to rid a text for repeated exclamation marks (!!!), question marks (??) or full stops (....) and replace them with a single instance of themselves. 我想删除重复感叹号(!!!),问号(??)或句号(....)的文本,并用自己的单个实例替换它们。 So I need "one preg_replace to rule them all" basically. 所以我基本上需要“一个preg_replace来统治它们”。

I currently have three separate patterns being executed: 我目前有三个独立的模式正在执行:

preg_replace("/[!]{2,}/","!", $str);
preg_replace("/[?]{2,}/","?", $str);
preg_replace("/[.]{2,}/",".", $str);

Is there a way to replace the found character with a single instance of itself using just one regex pattern? 有没有办法用一个正则表达式模式用一个单独的实例替换找到的字符?

I need to turn: 我需要转:

Ok!!!
Really????
I guess.....

into: 成:

Ok!
Really?
I guess.

With one regex pattern. 有一个正则表达式模式。

Use a capturing group with a backreference: 使用具有反向引用的捕获组:

([?!.])\1+

Replace with $1 . 替换$1

See the regex demo. 请参阅正则表达式演示。

Details 细节

  • ([?!.]) - matches and captures into Group 1 a single char: ? ([?!.]) - 匹配并捕获第1组中的单个字符: ? , ! ! or . .
  • \\1+ - matches one or more instances of the content captured into Group 1. \\1+ - 匹配捕获到组1中的一个或多个内容实例。

PHP demo : PHP演示

$str = "Ok!!!\nReally????\nI guess.....";
$res = preg_replace('/([?!.])\1+/', '$1', $str);
echo $res;

Results: 结果:

Ok!
Really?
I guess.

Just for completion, I thought I'd post my own answer based on my original code after viewing the answer given by another. 为了完成,我想在查看另一个人给出的答案后,我会根据原始代码发布自己的答案。

 pattern ([!?.]){2,}

 preg_replace('/([!?.]){2,}/','$1', $str);

This pattern also seems to work fine. 这种模式似乎也很好。

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

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