查找页面中的链接并通过自定义功能运行它

查找页面中的链接并通过自定义功能运行它

问题描述:

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

这就是工作代码。查找页面中的链接并通过自定义功能运行它

我工作的一个新功能

function shorturl2full($url) 
{ 
    echo 'URL IS: ' . $url; 
    return "FULLLINK"; 
} 

的想法是采取URL,然后返回。稍后将着手将其转换为完整的网址。所以像t.co将是他们将看到的完整网址。

$text= preg_replace("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a href=\"$3\" target=\"_blank\">" . shorturl2full("$3") . "</a>", $text); 
     $text= preg_replace("/(^|[\n ])([\w]*?)((www|ftp)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"http://$3\" target=\"_blank\">" . shorturl2full("$3") . "</a>", $text); 
     $text= preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a href=\"mailto:[email protected]$3\" target=\"_blank\">[email protected]$3</a>", $text); 
     return($text); 
} 

是我的坏尝试。

所以,如果你点击链接,应该用原来的,但你看到的应该是shorturl2full

输出所以像<a href="t.co">FULLLINK</a>

我想尝试写我自己的shorturl2full功能我想我对如何做到这一点有非常好的想法。问题出在link_it函数中......它需要将url传递给shorturl2full函数并显示它返回的内容。

可以使用preg_replace_callback代替了preg_replace http://nz.php.net/manual/en/function.preg-replace-callback.php

function link_it($text) 
{ 
    $text= preg_replace_callback("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", 'shorturl2full', $text); 
    $text= preg_replace_callback("/(^|[\n ])([\w]*?)((www|ftp)\.[^ \,\"\t\n\r<]*)/is", 'shorturl2full', $text); 
    $text= preg_replace_callback("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", 'shorturl2full', $text); 
    return($text); 
} 

function shorturl2full($url) 
{ 
    $fullLink = 'FULLLINK'; 
    // $url[0] is the complete match 
    //... you code to find the full link 
    return '<a href="' . $url[0] . '">' . $fullLink . '</a>'; 
} 

希望这有助于

previous answer我展示了一个名为make_clickable功能,如果有设置其中获得套用至每个URI一个可选的回调参数:

make_clickable($text, 'shorturl2full'); 

也许是有益的,或者至少给出了一些想法。