Jump to content

Automatic Hyperlink


mpridham

Recommended Posts

Hi Folks,

 

I have created a very simple blog application and would like to add the functionality of having hyperlinks automatically created when a url is entered. For instance, when I post a blog entry with something like "Go to www.foobar.com", I would like it to automatically add the anchor tags (like this site does.)

 

Any ideas?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/140233-automatic-hyperlink/
Share on other sites

If I understand correctly...

 

$str = 'go to http://foobar.com/somefolder/somefile.php';
echo $str . '<br />'; // output initial string without embedded link
$str = preg_replace('#([^\s]+(?:http://(?:www)?)?\.[^\s]+)#', "<a href=\"$1\">$1</a>", $str);
echo $str; // output string again with embedded link

 

Is this along the lines of what you are asking for?

 

EDIT - There are issues depending on what else is in the sentence.. I'll work on that.. in the meantime, this *should* do it... brb

Link to comment
https://forums.phpfreaks.com/topic/140233-automatic-hyperlink/#findComment-734287
Share on other sites

Ok, here is a revision that I think will work better..

 

$str = 'To see the star.jpg file, go to http://www.foobar.com/somefolder/somefile.php/ for something cool!';
echo $str . '<br />';
$str = preg_replace('#([^\s]+(?:http://(?:www)?)?\.(?!jpe?g|gif|png|bmp)[^\s]+)#', "<a href=\"$1\">$1</a>", $str);
echo $str;

 

This way, if there is a mention of a file format outside of the url, it should not be taken into consideration for being converted into a link. You can add any additional potential problematic formats to (?!jpe?g|gif|png|bmp) if need be (be it image or video).

 

Link to comment
https://forums.phpfreaks.com/topic/140233-automatic-hyperlink/#findComment-734301
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.