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
https://forums.phpfreaks.com/topic/98199-text-to-url/
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
https://forums.phpfreaks.com/topic/98199-text-to-url/#findComment-502495
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.