Reputation: 231
String: this is text :wall: :wall: :wall: :wall: more text
Output should be: this is text :wall: more text
Task: Reduce the word :wall: to only 1.
I tried these both ideas, but didn't work:
$post_message = preg_replace("/([\:wall:])+/", "\\1", $post_message);
$post_message = preg_replace('/:wall:/', '', $post_message, 1);
Upvotes: 0
Views: 345
Reputation: 913
$str = 'this is text :wall: :wall: :wall: :wall: more text';
$post_message = preg_replace("#(:wall:\s+)+#i", '\1', $str);
Upvotes: 0
Reputation: 231
Accordingliy to the top solution:
I need:
String1: this is text :( :( :( more text
String2: this is text :? :? :? more text
Output should be: this is text :( more text
Output should be: this is text :? more text
Task: Reduce the smilie :( to only 1.
Task: Reduce the smilie :? to only 1.
I tried these, but didn't work:
$post_message = preg_replace('~(:()(?:\s+\1)+~', '$1', $post_message);
$post_message = preg_replace('~(:?)(?:\s+\1)+~', '$1', $post_message);
Thanks again.
Upvotes: 0
Reputation: 174706
Use the below regex in preg_replace
function.
Regex:
(:wall:)(?:\s+:wall:)+
OR
(:wall:)(?:\s+\1)+
Replacement string:
$1
Code:
<?php
$str = "this is text :wall: :wall: :wall: :wall: more text";
echo preg_replace('~(:wall:)(?:\s+\1)+~', '$1', $str);
?>
Output:
this is text :wall: more text
(:wall:)
Captures the text :wall:
into a group. This could be referred by group index 1. So this (?:\s+\1)+
matches the folowing one or more space + :wall:
strings. Replacing the match with the chars inside group index 1 will remove all the duplicate :wall:
strings.
Upvotes: 1
Reputation: 67968
(:wall:)(?=((?!\1).)*\1)
Try this.Replace by empty string
.See demo.
http://regex101.com/r/lZ5mN8/62
Upvotes: 0