我有一个脚本,使链接(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