Jump to content

When displaying text, how do I recognize & <a href> a hyperlink?


jasonwisdom

Recommended Posts

Hi,

 

I am coding a website.. where users type in a message, and it displays for the public.

Standard PHP 5.2.5.

 

When the text contains a hyperlink,

I want to wrap an <a href="link"> </a> around it.

How do I detect such a thing....is there a regular expression I can use?

 

Thanks for saving me time.

Jason

 

From the PHP manual user contrib

 

I thought that someone could use this hyperlink function.

preg_replace is about 6 times faster than ereg_replace. I took the original example from the ereg_replace function page and modified so that it works perfect. I gave a comment of what it matches.

One thing is that I added a space at the beginning so that only links that don't have <a href="" around them or anything else touching will be replaced.

 

<?php
function hyperlink(&$text)
    {
       // match protocol://address/path/file.extension?some=variable&another=asf%
       $text = preg_replace("/\s(([a-zA-Z]+:\/\/)([a-z][a-z0-9_\..-]*[a-z]{2,6})([a-zA-Z0-9\/*-?&%]*))\s/i", " <a href=\"$1\">$3</a> ", $text);
   
       // match www.something.domain/path/file.extension?some=variable&another=asf%
       $text = preg_replace("/\s(www\.([a-z][a-z0-9_\..-]*[a-z]{2,6})([a-zA-Z0-9\/*-?&%]*))\s/i", " <a href=\"http://$1\">$2</a> ", $text);
      
       return $text;
    }
?>

 

Play around with it and see how it works.

Courtesy of AmazingDiscoveries.org

God bless, Iasmin Balaj

I just went through this.  Perhaps this will help you:

 

<?php
$body = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '<a href="\\1">\\1</a>', $body); 
$body = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '\\1<a href="http://\\2">\\2</a>', $body);
?>

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.