-1

Possible Duplicate:
Find url from string with php

I found this code: but 2 link did not make properly. save my code in a php file for testing.

$a = <<<_END
www.coders.com/coder6602.html => Work
www.avan.ir?a=21 => Work
www.limited.ndot.in/kansas/#?w=500 => Not Work
http://www.sales.com => Work
http://www.mediafire.com/?298nlpla3eys9g6 => Work
http://diary.com/files/draft.html و  http://www.logo.net/plogo.swf => Not Work (this is two link)
_END;
/*
<a href="http://limited.ndot.in/kansas/">limited.ndot.in/kansas/</a>#?w=500

<a href="http://diary.com/files/draft.html و  logo.net/plogo.swf">diary.com/files/draft.html و  logo.net/plogo.swf</a>
*/
function strHyperlink($str){
    $pattern_url = '~(?>[a-z+]{2,}://|www\.)(?:[a-z0-9]+(?:\.[a-z0-9]+)?@)?(?:(?:[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])(?:\.[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])+|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?:/[^\\/:?*"<>|\n]*[a-z0-9])*/?(?:\?[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?(?:&[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?)*)?(?:#[a-z0-9_%.]+)?~i';

    $str = preg_replace('/http:\/\//','www.', $str);
    $str = preg_replace('/www.www./','www.', $str);
    $str = preg_replace($pattern_url,"<a href=\"http://\\0\">\\0</a>", $str);
    return preg_replace('/www./','',$str);
}
echo strHyperlink($a);
Community
  • 1
  • 1
Hamidreza
  • 1,639
  • 4
  • 26
  • 36
  • Well, obviously the pattern that you're using is not "perfect" :) Try this: http://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url – Nir Alfasi Feb 09 '12 at 19:07

1 Answers1

2

Use this regex: \b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))

You can test it on: http://gskinner.com/RegExr/

I have just tested this regex with your url's and works perfectly.

Richard
  • 4,038
  • 5
  • 30
  • 50