2010-11-18 62 views
9

我有一个功能,将在链接之前添加<a href>标记,链接之后添加</a>。但是,对于某些网页而言,它会中断。你将如何改进这个功能?谢谢!PHP - 将链接添加到字符串中的URL

function processString($s) 
{ 
    // check if there is a link 

    if(preg_match("/http:\/\//",$s)) 
    { 
     print preg_match("/http:\/\//",$s); 


     $startUrl = stripos($s,"http://"); 

     // if the link is in between text 
     if(stripos($s," ",$startUrl)){ 
      $endUrl = stripos($s," ",$startUrl); 
     } 
     // if link is at the end of string 
     else {$endUrl = strlen($s);} 

     $beforeUrl = substr($s,0,$startUrl); 
     $url = substr($s,$startUrl,$endUrl-$startUrl); 
     $afterUrl = substr($s,$endUrl); 

     $newString = $beforeUrl."<a href=\"$url\">".$url."</a>".$afterUrl; 

     return $newString; 
    } 

    return $s; 
} 
+0

正则表达式是有点草率,但我投入的99%,将有正确的网址,如果有的话 – AlexBrand 2010-11-18 16:53:15

+4

它打破什么网页? – 2010-11-18 16:54:15

+0

开始时你也会测试https,但稍后会忽略“s”。不知道,如果这导致这个错误,因为我也不知道,哪些页面被破坏;) – KingCrunch 2010-11-18 16:58:39

回答

18
function processString($s) { 
    return preg_replace('/https?:\/\/[\w\-\.!~#?&=+\*\'"(),\/]+/','<a href="$0">$0</a>',$s); 
} 
+0

我想缺少一个“=”:当url包含get参数时失败。我只是在“&”后面添加它,现在它工作: 'preg_replace('/ https?:\/\/[\ w \ - \。!〜?&= + \ * \'“(),\ /] + /','$0',$ s)' – Narcolessico 2012-05-16 08:43:55

+4

您忘记了#内部的地址 - 所以更正确的版本是'preg_replace('/ https?:\/\/[\ w \ - \。!〜# ?&= + \ * \'“(),\ /] + /','$0',$ text)' – 2013-03-21 13:10:10

+0

我刚刚编辑了答案以反映这两个补充。 – 2014-07-24 07:23:08

1

它打破了对包含 “特殊” 的HTML字符的所有URL。为了安全起见,在将它们连接在一起之前,先通过htmlspecialchars()传递这三个字符串组件(除非你想允许HTML之外的HTML)。

1
function processString($s){ 
    return preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@', '<a href="$1">$1</a>', $s); 
} 

发现here

+0

failed here:' http://www.xyz.com/~this-does-not-work!' – stillstanding 2010-11-18 17:12:40

+0

匹配“a ... a” - 奇怪 – AlexBrand 2010-11-18 18:51:06

+0

同样的情况我需要它在jquery/Javascript中。任何人都可以帮忙吗? – Yuv 2014-08-27 08:38:10