0

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. 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

Community
  • 1
  • 1
TheTechGuy
  • 16,560
  • 16
  • 115
  • 136

2 Answers2

0

Replace \?+ with ?, !+ with !, (\?!)+ with ?!, and so on.

function dedup_punctuation($str) {
  $targets      = array('/\?+/', '/!+/', '/(\?!)+/');
  $replacements = array('?'    , '!'   , '?!'      );
  return preg_replace($targets, $replacements, $str);
}
erisco
  • 14,154
  • 2
  • 40
  • 45
  • This works but is there a way to find repetitive pattern automatically with using back reference etc? For this I have to enter every use case separately. – TheTechGuy Mar 09 '17 at 05:17
0

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.

MahdiY
  • 1,269
  • 21
  • 32
  • can this improved to use bunch of punctuation [.!?] and find repetitive pattern automatically? – TheTechGuy Mar 09 '17 at 05:20
  • 1
    Code updated. To delete any repetitive sign, add it to replacement array. – MahdiY Mar 09 '17 at 05:36
  • btw can you think of a way to find the repetitive pattern by itself as asked in this [question](http://stackoverflow.com/questions/28963384/finding-the-shortest-repetitive-pattern-in-a-string) and apply it in PHP? I tried but failed. – TheTechGuy Mar 09 '17 at 07:02