Jump to content

Converting text to a hyperlink in PHP


LordLanky

Recommended Posts

Hi All,

 

hopefully a simple one - i'm letting people write comments on a page of mine by storing it in a mySQL database. I was hoping that when i output the comments, there would be a PHP function that will go "Oh, there's a URL - i'll convert that top a hyperlink!"

 

Does anyone know any quick ways of doing it? I'm not letting users input anything but plain text you see.....

 

many thanks!

Link to comment
https://forums.phpfreaks.com/topic/166074-converting-text-to-a-hyperlink-in-php/
Share on other sites

Yes, use a regular expression to find all matches within a string.

preg_match_all()

Then replace with the url surrounded by A tags using preg_replace()

 

You are obviosly looking for anything starting with http:// or https:// and ending when a space, newline occurs

Thanks Neil... i'm new to things like regexes and preg_replace... dont suppose you could show me an example?

 

lets say a variable $poopoo = "I really think you should go to www.showmeadog.com to find out more"

 

So the text www.showmeadog.com becomes the hyperlink!

 

Thanks matey,

i have found this:

 

$body = ereg_replace("http://([a-zA-Z0-9./-]+)$", "<a href=\"\\0\">\\0</a>", $row['item']);

 

But from my limited understanding, that just meand anything that begins with "http://" will be converted. however, what i would rather is that if a string starts with http:// OR if a string starts with www AND ends in .co.uk, or .com, or ... whatever......

 

Any ideas?

 

 

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

Yes a url will need to start with http:// or https://

If you want to match www. without the http:// then you need to add the http:// to the url for the A tag.

Get a tool like regexbuddy to help you write a pattern match.

 

To apply http:// to a string:

function addHttp($url) {
if(!eregi("^https?://", trim($url))) {
   $url = "http://" . $url; 
}
return $url;
}

$url = addHttp("www.google.com");

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.