Jump to content

Text to URL


The Little Guy

Recommended Posts

I would like to convert:

 

http://somewebsite.com

 

to

 

<a href="http://somewebsite.com">http://somewebsite.com</a>

 

and leave these alone:

 

<a href="http://somewebsite.com">http://somewebsite.com</a>
<a href="http://somewebsite.com">My Web Site</a>

 

 

I just need to turn the non-clickable URL's to Clickable URL's

Link to comment
Share on other sites

<?php

$subject = '<a href="http://somewebsite.com">http://somewebsite.com</a>
or another example is
this should work http://somewebsite.com okay
and just to make usre
<a href="http://somewebsite.com">http://somewebsite.com</a>';

$result = preg_replace('%(?<!(?:href=")|(?:">))(http://[^\s]++)%', '<a href="$1">$1</a>', $subject);

echo $result;

?>

 

That is a very loose example, and should be tightened up a bit better for production use.

 

In english, it finds anything that matches http:// and then grabs everything until a whitespace character shows up (linebreak, space, tab, ect). It then makes sure that before the string, there's no href=" or "> before it...

 

So if you entered <a href="somesite.php">This is http://someurl.com</a> the http://someurl.com would get parsed and converted. It's very VERY tricky to efficiently match against every possible entry. This should cover the basics though.

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.