Jump to content

Function To Automatically Create Links


JustinK101

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

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.