[英]PHP: Regexp to change urls
我正在尋找可以將我的字符串從以下位置更改的正則表達式:
text text website.tld text text anotherwebsite.tld/longeraddress text http://maybeanotheradress.tld/file.ext
變成bbcode
text text [url=website.tld]LINK[/url] text text [url=anotherwebsite.tld/longeradress]LINK[/url] text text [url=http://maybeanotheradress.tld/file/ext]LINK[/url]
你能請教嗎?
甚至我也投票贊成重復,這是一個普遍的建議: 分而治之 。
在您的輸入字符串中,所有“ URL”都不包含任何空格。 因此,您可以將字符串分成不包含空格的部分:
$chunks = explode(' ', $str);
我們知道每個部分現在都可能是一個鏈接,您可以創建自己的函數,該函數可以這樣說明:
/**
* @return bool
*/
function is_text_link($str)
{
# do whatever you need to do here to tell whether something is
# a link in your domain or not.
# for example, taken the links you have in your question:
$links = array(
'website.tld',
'anotherwebsite.tld/longeraddress',
'http://maybeanotheradress.tld/file.ext'
);
return in_array($str, $links);
}
in_array
只是一個示例,您可能正在尋找基於正則表達式的模式匹配。 您可以稍后對其進行編輯以滿足您的需要,我將其保留為練習。
現在您可以說什么是鏈接,什么不是,剩下的唯一問題是如何從鏈接中創建BBCode,這是一個相當簡單的字符串操作:
if (is_link($chunk))
{
$chunk = sprintf('[url=%s]LINK[/url]', $chunk);
}
因此,從技術上講,所有問題都已解決,需要將這些問題放在一起:
function bbcode_links($str)
{
$chunks = explode(' ', $str);
foreach ($chunks as &$chunk)
{
if (is_text_link($chunk))
{
$chunk = sprintf('[url=%s]LINK[/url]', $chunk);
}
}
return implode(' ', $chunks);
}
這已經與您的問題示例字符串( Demo )一起運行:
$str = 'text text website.tld text text anotherwebsite.tld/longeraddress text http://maybeanotheradress.tld/file.ext';
echo bbcode_links($str);
輸出:
text text [url=website.tld]LINK[/url] text text [url=anotherwebsite.tld/longeraddress]LINK[/url] text [url=http://maybeanotheradress.tld/file.ext]LINK[/url]
然后,您只需要調整is_link
函數即可滿足您的需求。 玩得開心!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.