1

I am allowing people to post comments using a textarea field and sometimes they post urls. What I need to do is to convert this url from db before displaying it as a real clickable link, but without allowing html tags. I would prefer to do it using php or jquery if possible. I thought about using something like [link][/link] but I need to do it without any extra effort from the website member. Any ideas please??

example :

[link]http://www.google.com[/link]
Tim Gautier
  • 29,150
  • 5
  • 46
  • 53
wfareed
  • 139
  • 2
  • 17
  • Possible duplicate of http://stackoverflow.com/questions/8188645/javascript-regex-to-match-a-url-in-a-field-of-text and http://stackoverflow.com/questions/1959062/how-to-add-anchor-tag-to-a-url-from-text-input – j08691 Jan 13 '12 at 20:43
  • possible duplicate of [php html create link from text](http://stackoverflow.com/questions/5252727/php-html-create-link-from-text) – s4y Jan 13 '12 at 20:44

4 Answers4

1

Here is a little PHP script that I have written. It seems to work for me. It uses the preg_match_all and preg_replace methods to match all the links inserted by the end user with <a> tags.

<?php

$text="Click [link]http://www.google.com[/link] or click [link]http://www.yahoo.com[/link]";

preg_match_all('/\\[link](.*?)\\[\/link]/s', $text, $links);

$link_count=count($links);
for($i=0;$i<$link_count;$i++){
    $link_url=preg_replace("/\[link]/", "", $links[0][$i]);
    $link_url=preg_replace("/\[\/link]/","",$link_url);
    $text=str_replace($links[0][$i],"<a href=\"" . $link_url . "\">" . $link_url . "</a>",$text);
}

echo $text;

?>
siberiantiger
  • 305
  • 1
  • 3
  • 10
0

use regex to find urls within the block of text, then append and prepend the necessary tags

http://www.regexguru.com/2008/11/detecting-urls-in-a-block-of-text/

Ethan
  • 2,754
  • 1
  • 21
  • 34
0

You may or may not be interested in this software: http://markitup.jaysalvat.com/examples/bbcode/

Kyle Macey
  • 8,074
  • 2
  • 38
  • 78
0

You can use preg_replace method:

//URL's
$pattern = "/\[link\=(.*)\](.*)\[\/link\]/i";
$replace = "<a href=\"$1\">$2</a>";
echo preg_replace($pattern, $replace, $subject); 
Nazariy
  • 6,028
  • 5
  • 37
  • 61