tags:

views:

59

answers:

2

I have a guestbook, and I want to convert site address in the following [link]www.yahoo.com[/link] to <a>...

So how is it do that str_replace?

+1  A: 

str_replace is not powerful enough to do this. You can use preg_replace:

$res = preg_replace('#\\[link\\](?![^:]+script:)([^:<"\\[]+:)?([^<"\\[]+)\\[/link\\]#e',
                    "'<a href=\"'.('\\1'?'\\1':'http://').'\\2\"&gt;click here</a>'",
                    $input);

Example: http://www.ideone.com/lTknX

But it's better to use a BBCode parser.

KennyTM
+1 to the idea of using a BBCode parser. If you try to implement this yourself you will run into edge cases that won't work until you implement a full state machine-based parser.
Jon Cram
The linked BBCode parser is a *PECL extension*, and is not built-in to PHP.
Charles
A: 

This should do that for you:

$string = "[link]www.yahoo.com[/link]";

echo preg_replace("/\[link\](.*)\[\/link\]/", "<a href='$1'>click here</a>", $string);
xil3