hey guys, i got a code that convert links entered through a textarea to a clickable link with page title as shown string
like this:
<a href=“enteredURL” rel=“nofollow”>pageTitle</a>
I wanna know if the code below looks all right to you? it works only for some links not all, and i dont know the reason.
function get_page_title($url)
{
ini_set('user_agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11');
if(!($data = @file_get_contents($url)))
return false;
if(preg_match("#<title>(.+)<\\/title>#iU", $data, $t))
return trim($t[1]);
return false;
}
function _make_url_clickable_cb($matches)
{
$ret = '';
$url = $matches[2];
if (empty($url))
return $matches[0];
if (in_array(substr($url, -1), array('.', ',', ';', ':')) === true)
{
$ret = substr($url, -1);
$url = substr($url, 0, strlen($url)-1);
}
$x = get_page_title($url);
if (!$x)
$x = 'link';
return $matches[1] . "<a href=\\"$url\\" rel=\\"nofollow\\">$x</a>" . $ret;
}
function _make_web_ftp_clickable_cb($matches)
{
$ret = '';
$dest = $matches[2];
$dest = 'http://' . $dest;
if (empty($dest))
return $matches[0];
if (in_array(substr($dest, -1), array('.', ',', ';', ':')) === true)
{
$ret = substr($dest, -1);
$dest = substr($dest, 0, strlen($dest)-1);
}
$x = get_page_title($dest);
if (!$x)
$x = 'link';
return $matches[1] . "<a href=\\"$dest\\" rel=\\"nofollow\\">$x</a>" . $ret;
}
function make_clickable($ret)
{
$ret = ' ' . $ret;
$ret = preg_replace_callback('#([\\s>])([\\w]+?://[\\w\\\\x80-\\\\xff\\#$%&~/.\\-;:=,?@\\[\\]+]*)#is', '_make_url_clickable_cb', $ret);
$ret = preg_replace_callback('#([\\s>])((www|ftp)\\.[\\w\\\\x80-\\\\xff\\#$%&~/.\\-;:=,?@\\[\\]+]*)#is', '_make_web_ftp_clickable_cb', $ret);
$ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
$ret = trim($ret);
return $ret;
}
An example of link which it fails to convert is this:
http://www.yad2.co.il/Order/Order2_Pet.php
The result given for the link above is:
<a href=“http://www.yad2.co.il/Order/Order2_Pet.php” rel=“nofollow”>
so it gets stucked somewhere at getting the title … any help?
Thanks,
ulthane