Skip to content
Advertisement

replace full bbcode tag by empty not working php

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

$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

 $string = preg_replace("[MSG='(.*?)'](.*?)[/MSG]", "M", $string);

EXPECTED OUTPUT

 hello M M M M M hello

Im using this regex [MSG='(.*?)'](.*?)[/MSG] what is wrong with it?

Advertisement

Answer

Try this regex

or

$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;
 hello M M M M Mhello
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement