2011-02-28 48 views
1

有很多类似的问题,但我尝试了大约15个不同的preg_match示例,但都没有完全工作。将www或http开头的多个文本网址转换为绝对链接

我有很多用户提交的内容,其中大部分都有url ..有时以http://www.site.com/page的形式,有时像www.site.com,并且经常包含在括号内(www.site.com/page.html) 。

我没有找到一种模式来解析一个字符串,并将所有这些转换为绝对html链接。想知道是否有人可以帮助我。我发现了几个正则表达式,似乎他们会工作,但我不知道如何正确转换为绝对html链接,当有一些与http和一些没有...

这里有几个表达式,我曾尝试:

function makeLinks($text) { 
    $text = preg_replace('(((f|ht){1}tp://)[[email protected]:%_\+.~#?&//=]+)', 
     '(<a href="\\1">\\1</a>)', $text); 
    $text = preg_replace('(www\.[a-zA-Z0-9\-]\.[^ ]+)', 
     '(<a href="\\1">\\1</a>)', $text); 

     return $text; 
} 

function makeLinks($text) { 
    $text = preg_replace('~(?:www|http://)\S+~', '<a href="$0">$0</a>', $text); 

     return $text; 
} 

function makeLinks($text) { 
    $text = preg_replace('@(?<![.*">])\b(?:(?:https?|ftp|file)://|[a-z]\.)[-A-Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]@i', '<a href="\0" target="_blank">\0</a>', $text); 

     return $text; 
} 
+0

很抱歉,但也许有些样品代码将有助于解释你正在努力达到的目标。就像你之前的代码一样,你说你试过了。 – burntblark 2011-02-28 07:54:06

+0

以www或http开头的网址是绝对链接。我不确定你想要完成什么。现在,没有http://的地址可能不会被正确解释(由古老的/破碎的浏览器),但无论这些都是绝对链接,添加“http://”的正则表达式将是微不足道的。再一次,我不明白你的问题。你能否详细说明一下? – rockerest 2011-02-28 08:17:43

+0

或者,也许你想从你的网址中删除域名+协议 – burntblark 2011-02-28 09:42:05

回答

2

我结束了使用此字符串,这似乎在所有必要的情况下将表现良好:

function makeLinks($text) { 
    $text = preg_replace('%(((f|ht){1}tp://)[-a-zA-^[email protected]:\%_\+.~#?&//=]+)%i', 
    '<a href="\\1">\\1</a>', $text); 
    $text = preg_replace('%([[:space:]()[{}])(www.[[email protected]:\%_\+.~#?&//=]+)%i', 
    '\\1<a href="http://\\2">\\2</a>', $text); 

     return $text; 
} 
+0

You have to add ! and , in your regex and add [s]? in the first preg for https : '$text = preg_replace('%(((f|ht){1}tp[s]?://)[-a-zA-^[email protected]:\%_\+.,!~#?&//=]+)%i','\\1',$ text); $ text = preg_replace('%([[:space:]()[{}])(www。[ - a-zA-Z0-9 @:\%_ \ +。,!〜#?&//=] +)%i','\\ 1 \\2',$ text);' 因为有,而!在一些网址(例如metronews.fr) – zeuf 2014-05-28 11:03:15

+0

我必须添加)和(也在正则表达式中, – zeuf 2014-06-19 13:54:25

+0

我必须添加; – zeuf 2015-02-06 11:17:29

0

这是一个良好的开端:

function makeLinks($text) { 
    $text = preg_replace('~(?:www|http://)\S+~', '<a href="$0">$0</a>', $text); 
    return $text; 
} 

$ 0是全场比赛。如果您只对不带http://www.http://www.的部分进行分组,则可以将其连接到前端。

试试这个,如果你还在寻找一个答案:

function makeLinks($text) { 
    $text = preg_replace('~(?:http://|)(?:www\.|)(\S+)~', '<a href="http://www.$1">$0</a>', $text); 
    return $text 
} 
+0

that didn't work for me... it turned every word into a hyperlink – Damon 2011-03-06 02:46:02

+1

Oh sorry try '~\b(?:http://www.|http://(?!www.)|(? RedSoxFan 2011-03-07 00:13:30

+0

I am not getting expected result. Please use the proper variables inside functional flow. ex: ($tect, $text, $test) used to indicate single variable. – Navane 2013-03-14 16:01:35