PHP Replace

Joined
Dec 10, 2006
Messages
540
I have a string that I need to replace part of.
For example I have:
$string = "A link will go [link:http://google.com]Here[/link] and some more text here";

I want to change [link:%url%]%text%[/link] to <a href="%url%">%text%</a> no matter what the url and text are. How can I do this? I am unsure how to do it with a str_replace or preg_replace
 
if you're not familiar with regular expressions you probably won't understand what it does but here's what i would do.
Code:
$str = preg_replace('!\[link:([^\]]+)\]([^\[]+)\[/link\]!i', '<a href="$1">$2</a>', $str);
haven't tested it but something along those lines.

it took me a long time to wrap my head around regular expressions.
 
Doing regular expressions like this can get kinda hairy once you start looking at all the sorts of error conditions and weird nesting that might pop up. Fortunately, there's a bbcode module that, if you have a new enough install of PHP, should handle things for you.

I haven't tried it, but it might save you some time & help you avoid common mistakes.
 
^ definitely. it always depends on the situation. if you /only/ ever want to do links, using a regex is probably the simplest and quickest solution, but if you want the ability to add different formatting later on, then using regexes quickly becomes tedious and bad performance-wise and you should look into a full fledged parser.
 
Back
Top