我有一個腳本,使鏈接(http,https和www)在一個句子中可點擊。問題是我只能有一個鏈接。我可以通過任何類型的if語句中的循環來解決這個問題嗎?PHP通過正則表達式匹配文本超鏈接
$text = "Both www.google.com and http://www.google.com/calendar/ are links";
/**
* Make clickable links from URLs in text.
*/
function make_clickable($text) {
// Force http to www.
$text = preg_replace("(www\.)", "http://www.", $text);
// Delete duplicates after force.
$text = preg_replace("(http://http://www\.)", "http://www.", $text);
$text = preg_replace("(https://http://www\.)", "https://www.", $text);
// The RegEx.
$regExUrl = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// Check if there is a URL in the text.
if(preg_match($regExUrl, $text, $url)) {
// Make the URLs hyper links.
$text = preg_replace(
$regExUrl,
'<a href="' . $url[0] . '" target="_blank">' . $url[0] . '</a>',
$text
);
}
return $text;
}
echo make_clickable($text);
結果: 兩個http://www.google.com和http://www.google.com是鏈接
在此先感謝。
到底是什麼問題了嗎?這似乎正在按預期工作... – 2014-11-20 22:17:02
不,請查看變量中的輸入鏈接。輸出只是給了我兩個(兩次)的第一個鏈接。如果輸入是http://stackoverflow.com/和http://google.com,我將獲得兩次http://stackoverflow.com/。因此,我想可能需要一個循環。你明白嗎? – Treps 2014-11-20 22:20:16