I have a script that outputs status updates and I need to write a script that automatically changes something like www.example.com
into a hyper link in a chunk of text like Twitter and Facebook do. What functions can I use for this in PHP? If you know a tutorial please post i开发者_StackOverflow社区t.
$string = " fasfasd http://webarto.com fasfsafa";
echo preg_replace("#http://([\S]+?)#Uis", '<a rel="nofollow" href="http://\\1">\\1</a>', $string);
Output:
fasfasd <a rel="nofollow" href="http://webarto.com">webarto.com</a> fasfsafa
You can use a regex to replace the url with a link. Look at the answers on this thread: PHP - Add link to a URL in a string.
Great solution!
I wanted to auto-link web links and also to truncate the displayed URL text, because long URLs were breaking out of the layout on some platforms.
After much fiddling around with regex, I realised the solution is actually CSS - this site gives a simple solution using CSS white-space.
Here is the working Function
function AutoLinkUrls($str,$popup = FALSE){
if (preg_match_all("#(^|\s|\()((http(s?)://)|(www\.))(\w+[^\s\)\<]+)#i", $str, $matches)){
$pop = ($popup == TRUE) ? " target=\"_blank\" " : "";
for ($i = 0; $i < count($matches['0']); $i++){
$period = '';
if (preg_match("|\.$|", $matches['6'][$i])){
$period = '.';
$matches['6'][$i] = substr($matches['6'][$i], 0, -1);
}
$str = str_replace($matches['0'][$i],
$matches['1'][$i].'</xmp><a href="http'.
$matches['4'][$i].'://'.
$matches['5'][$i].
$matches['6'][$i].'"'.$pop.'>http'.
$matches['4'][$i].'://'.
$matches['5'][$i].
$matches['6'][$i].'</a><xmp>'.
$period, $str);
}//end for
}//end if
return $str; }
精彩评论