Link to home
Start Free TrialLog in
Avatar of rockmansattic
rockmansattic

asked on

problem with preg_replace

Should be easy ,

I have a string text from a database...

Exact databse text is   [b:5a076bc001] Steve Kaufman [/b:5a076bc001]
Where the [b:.. code is used for another application.  Here I want it to be <b>
so I attempt to do this like so:

<?php $announcement = $row_announcements['post_text'];
$patterns[0] = "[b:5a076bc001]";
$patterns[1] = "[/b:5a076bc001]";
$replacements[0] = "<b>";
$replacements[1] = "</b>";
echo preg_replace($patterns, $replacements, $announcement);?>

But this yeilds

[<b>]Steve Kaufmann[/<b>]
NOT <b>SteveKaufmann</b> As hoped

As you can see it is keeping the brackets, I have tried several things but no success.

thanks
Avatar of Diablo84
Diablo84

if this is all you need it to do you would be better off with str_replace

<?php $announcement = $row_announcements['post_text'];
$patterns[0] = "[b:5a076bc001]";
$patterns[1] = "[/b:5a076bc001]";
$replacements[0] = "<b>";
$replacements[1] = "</b>";
echo str_replace($patterns, $replacements, $announcement);?>
Well, first of all, you should know that [ and ] are special characters in Regex...
Second of all, here is a sniplet of a code I did to remove these kind of tags from PHPBB posts:

      //remove bbcode
      $row['post_text'] = preg_replace('/\\[((color|size)=.*|b|u|i|quote):.*\\]/Usi', '', $row['post_text']);
      $row['post_text'] = preg_replace('/\\[\\/(color|size|b|u|i|quote):.*\\]/Usi', '', $row['post_text']);
      $row['post_text'] = preg_replace('/\\[url(=.*)?\\]/Usi', '', $row['post_text']);
      $row['post_text'] = preg_replace('/\\[(\\/url|\\/img|img)\\]/Usi', '', $row['post_text']);

Here's what will do the work for you :)

$text = preg_replace('/\\[b:.*\\](.*)\\[\\/b:.*\\]/Usi', '<b>\\1</b>', $text);
ASKER CERTIFIED SOLUTION
Avatar of Boris Aranovich
Boris Aranovich
Flag of Israel image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rockmansattic

ASKER

Exactly what I needed.  thank you.  

also, thank you Diablo84,   What you have would work, but just nomaed stated (which is somthing I did not look to the future for) is that this code will change.

thank you again.
I know that those [b:1212312312] tags usually are annoying to me as well, so I am glad I could help :)