Jump to content

[SOLVED] Enclose URL in tags?


immanuelx2

Recommended Posts

Hey guys, wondering if someone could point me to a sample preg_replace() function that searches for an URL of any kind and encloses it in tags

 

The one I found so far is

<?php
$text = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $text);

 

but for some reason, if the URL contains a dash "-" it thinks the URL has ended.. ???

 

Thanks in advance

Link to comment
Share on other sites

kind of simple but it should do the trick most of the time....idea here is that if something starts with http:// or https:// then it's probably a url, so it just grabs everything up to the first space it finds.  The theory being that a url would not have a space in it (or it would be urlencoded so it wouldn't be a physical space char)

 

$text = preg_replace('~(https?://[^\s]+)~i','<a href= "$1">$1</a>',$text);

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.