Plain text link to HTML with a PHP function and regular expressions
If you have ever wanted to turn a plain text link, http://www.smjdesign.com, into a "linked" HTML version, http://www.smjdesign.com, you can now. Pass the following function your entire text field and it will find all your links and return tagged HTML.
function replace_plain_text_link($plain_text) {
$url_html = preg_replace(
'/(?<!S)((http(s?):\/\/)|(www.))+([\w.1-9\&=#?\-~%;\/]+)/',
'<a href="http$3://$4$5">http$3://$4$5</a>', $plain_text);
return ($url_html);
}
echo replace_plain_text_link("hi this is dummy text before
http://www.smjdesign.com hi this is dummy text after")
The majority of the above regular expression was not created by me. I however cannot locate the original programmer. It was posted on a message board I visited along with ftp and mailto options. If you can help, please comment.
Further Reading on HTML and CSS
- Hiding an email address from spambots and spiders
- CSSsprite: Photoshop script combines two images for CSS hover
- Features and characteristics of a great 404 error page






January 16th, 2009 at 12:15 pm
The script works good unless you have a longer url like http://www.myspace.com/wearemongrel than only http://www.myspace.com will be linked and /wearemongrel is left out in the cold
January 23rd, 2009 at 4:44 pm
@Michael It’s fixed now. Your example URL will now work. Thanks.
July 7th, 2009 at 2:44 pm
Great function, thanks. Saved me a bit of time messing about with regular expressions!
Matthew
February 11th, 2010 at 8:56 pm
Works, but not for every URL. For example, Google Maps links =) You would have to add a comma (and some other characters). Still found this useful, thanks.