I need to replace a full bbcode tag by an empty space (in this example by a “M”)
This is my php code so far
JavaScript
x
$string ="
hello
[MSG='user1, comment: 253434, userid: 1232'] TEXT1[/MSG]
[MSG='user2, comment: 343425, userid: 4231']
TEXT2
[/MSG]
[MSG='user3, comment: 234345, userid: 1423']
TEXT3
[/MSG]
[MSG='user4, comment: 253434, userid: 123242']
TEXT4
text 4
text 4
[/MSG]
[MSG='user5, comment: 251234, userid: 1652'] TEXT5[/MSG]
hello
";
regex replacement
JavaScript
$string = preg_replace("[MSG='(.*?)'](.*?)[/MSG]", "M", $string);
EXPECTED OUTPUT
JavaScript
hello M M M M M hello
Im using this regex [MSG='(.*?)'](.*?)[/MSG]
what is wrong with it?
Advertisement
Answer
Try this regex
or
JavaScript
$re = '/([MSG=.*?[/MSG]s+)/ms';
$str = '$string ="
hello
[MSG='user1, comment: 253434, userid: 1232'] TEXT1[/MSG]
[MSG='user2, comment: 343425, userid: 4231']
TEXT2
[/MSG]
[MSG='user3, comment: 234345, userid: 1423']
TEXT3
[/MSG]
[MSG='user4, comment: 253434, userid: 123242']
TEXT4
text 4
text 4
[/MSG]
[MSG='user5, comment: 251234, userid: 1652'] TEXT5[/MSG]
hello';
$subst = ' M';
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
JavaScript
hello M M M M Mhello