url - PHP: Properly convert addresses to clickeable links in string -


i need automatically parse string , find if link site present, automatically replace address clickeable html link.

supposing site adresses www.mysite.com + wap.mysite.com + m.mysite.com, need convert:

my pictures @ m.mysite.com/user/id great. 

to:

my pictures @ <a href="/user/id" target="_blank">mysite.com/user/id</a> great. 

the question how (with ereg_replace?) instead of using tons of lines of code.

notice result must relative url, current protocol , subdomain used target link. if user in m subdomain of https version, target m subdomain of https protocol , on. only links mysite.com must linked, other links must treated ordinary plain text. in advance!

first piece of advice, stay away ereg, it's been deprecated long time. second, can google , experiment concoct preg expression works you, tweak have here suit needs.

i able put simple regex pattern search urls.

preg_match("/m.mysite.com\s+/", $str, $matches); 

once have urls, i'd suggest parse_url instead of regex.

and here code

$ssampleinput = 'my pictures @ http://m.mysite.com/user/id great.';  // search urls don't scheme, we'll add later preg_match("/m.mysite.com\s+/", $ssampleinput, $amatches);  $aresults = array(); foreach($amatches $surl) {     // tack scheme afront url     $surl = 'http://' . $surl;      // try validating url, requiring host & path     if(!filter_var(         $surl,         filter_validate_url,         filter_flag_host_required|filter_flag_path_required)) {         trigger_error('invalid url: ' . $surl . php_eol);         continue;     } else         $aresults[] =             '<a href="' . parse_url($surl, php_url_path) .             '" target="_blank">' . $surl . '</a>'; } 

Comments