Jump to content

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");

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.