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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.