-1
function makeLinksInTheContent($html)
{
    $html= preg_replace("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a href=\"$3\" rel=\"nofollow\" >$3</a>", $html);
    $html= preg_replace("/(^|[\n ])([\w]*?)((www|ftp)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"http://$3\" rel=\"nofollow\" >$3</a>", $html);
    $html= preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a href=\"mailto:$2@$3\" rel=\"nofollow\">$2@$3</a>", $html);

    return($html);
}

this is my code.

My need is autolinking the url. Using preg_replace to find the url and set link to this url.

for example: "A page contains www.google.com." if i pass this content to makeLinksInTheContent($html), it will return "A page contains www.google.com."

But The following url format is not getting linked.

  1. (http://www.google.com)
  2. www.test.com()and[]&^%$#@!+|!@#$%^&()_+}{:"?><,./;'[]=-09~`.co,in,com.com
  3. http://www.test.com()and[]&^%$#@!+|!@#$%^&()_+}{:"?><,./;'[]=-09~`.co,in,com.com
  4. https://www.test.com()and[]&^%$#@!+|!@#$%^&()_+}{:"?><,./;'[]=-09~`.co,in,com.com
  5. ftp://www.test.com()and[]&^%$#@!+|!@#$%^&()_+}{:"?><,./;'[]=-09~`.co,in,com.com

I think my regular expression have some mistakes. please suggest us.

1 Answer 1

1

I can suggest using my function - just tested with your data and works for me

function parse_links($string,$mailto=true)
{
    $preg_r = "#(((https?|ftp)(://)?)?[a-zA-Z0-9-_.]{1,64}\.[a-zA-Z0-9-_.]{1,128}\.[a-z]{2,4}(\.[a-z]{2,4})?(/([^ ]{1,256}))?/?)#";
    $string = preg_replace($preg_r,"<a href=\"http://$1\">$1</a>",explode(" ",$string));
    if($mailto)
    {
        $preg_r2 = "/([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z_\-\.][-\w]*[0-9a-zA-Z_\-\.]\.)+[a-zA-Z]{2,9})/";
        $string = preg_replace($preg_r2,"<a href=\"mailto:$1\">$1</a>",$string);
    }
    return implode(" ",$string);
}

Just pass false as second parameter if you don't want email links to be created

Sign up to request clarification or add additional context in comments.

1 Comment

Damn good regex dude! I like the way you are conforming to Apache's (Could be web-wide) url standards with the length of the given url.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.