問題描述
我找到了在文本中找到鏈接時創(chuàng)建 html 鏈接的例程
I found a routine to create a html link when a link is found in a text
<?php
function makelink($text)
{
return preg_replace('/(http://[a-zA-Z0-9_-.]*?) /i', '<a href="$1">$1</a> ', $text." ");
}
// works
echo makelink ("hello how http://www.guruk.com ");
// dont work
echo makelink ("hello how http://www.guruk.com/test.php ");
?>
如您在示例中所見,它僅適用于域,而不適用于該鏈接中存在頁面或子目錄的情況.
as you see in the example, it works find with a domain only, not when there is a page or subdirectory is within that link.
您能否為該功能提供一個解決方案,使其也適用于頁面和子目錄?
Can you provide a solution for that function to work also with pages and subdirs?
謝謝克里斯
推薦答案
字符 ?=&
用于帶有查詢字符串的 url.請注意,我將分隔符從 /
更改為 !
因為您的表達(dá)式中有很多斜線.另請注意,如果您處于不區(qū)分大小寫的模式,則不需要 A-Z
.
The characters ?=&
are for urls with query strings. Notice that I changed the separator from /
to !
because there a lot of slashes in your expression. Also note that you don't need A-Z
if you are in case-insensitive mode.
return preg_replace('!(http://[a-z0-9_./?=&-]+)!i', '<a href="$1">$1</a> ', $text." ");
這篇關(guān)于php html 從文本創(chuàng)建鏈接的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!