Jump to content

Recommended Posts

Looking for help writing a function that does the following:

 

Look for http:// or https:// in a string and replaces it with an <a href> tag. For example:

 

Here is my link http://www.mydomain.com some further text here.

 

Becomes:

 

Here is my link <a href="http://www.mydomain.com">http://www.mydomain.com</a> some further text here.

Link to comment
https://forums.phpfreaks.com/topic/211985-function-to-automatically-create-links/
Share on other sites

Looking for help writing a function that does the following:

 

Look for http:// or https:// in a string and replaces it with an <a href> tag. For example:

 

Here is my link http://www.mydomain.com some further text here.

 

Becomes:

 

Here is my link <a href="http://www.mydomain.com">http://www.mydomain.com</a> some further text here.

 

 

This id pretty simple. All you have to do is:

 


$text="hello I am doing well http://www.google.com ok";
preg_match("/[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+/i",$text,$url);

$new= "<a href=\"$url[0]\">$url[0]</a>";

echo preg_replace("/[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+/i",$new,$text);



 

And you are done...

Un-tested

function stringToAnchor($str) {
return preg_replace('~((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)~','<a href="$1">$1</a>',$str);
}

//Testing
echo stringToAnchor('You can find the best deals at http://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.