Forum Moderators: coopster

Message Too Old, No Replies

String formating / preg_replace

Replace [link] * [/link] with <a href=*> * </a>

         

mcfly

6:18 pm on Oct 2, 2003 (gmt 0)

10+ Year Member



Does anyone have any idea how to implement a simple version of the common forum feature which allows a user to designate a link with [link] [/link] tags to be replaced with the appropriate html on submission of a form?

I currently upload users' articles to a database, and want to allow them to insert links without actually using html - presumably it's a relatively simple function but I haven't managed to come up with anything that works yet.

eg. [link]www.widgets.com[/link]
should go to
<a href="http://www.widgets.com">www.widgets.com</a>

I understand I could use preg_replace, or similar, to change [link] to <a href etc.>, but am stuck when it comes to 'extracting' the URL from the string, especially when there are multiple occurences within the string.

Any help would be great...

Thanks.

bcolflesh

6:36 pm on Oct 2, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Check this Google Groups posting:

groups.google.com/groups?q=hyperlink+%22regular+expression%22+group:php.general&hl=en&lr=&ie=UTF-8&safe=off&selm=3A248B2C.13ED233C%40analysisandsolutions.com&rnum=2

MonkeeSage

8:31 pm on Oct 2, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



$str = "[link]www.webmasterworld.com[/link]"; 
$str = preg_replace('/\[link\](.+)\[\/link\]/', "<a href=\"http://$1\">$1</a>", $str);
echo $str;

Jordan

NM.

[edit:] fixed post, thanks coopster [/edit]

[edited by: MonkeeSage at 8:49 pm (utc) on Oct. 2, 2003]

coopster

8:44 pm on Oct 2, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Missed something there ;)

$str = preg_replace('/\[link\](.+)\[\/link\]/', "<a href=\"http://$1\">$1</a>", $str);

Even so, bcolflesh has a very good point with the link he provided.

mcfly

8:32 am on Oct 3, 2003 (gmt 0)

10+ Year Member



Brilliant! Thanks very much for your suggestions guys. :)