PHP通过正则表达式匹配从文本生成超链接
我有一个脚本,使链接(http,https和www)在一个句子中可点击。问题是我只能有一个链接。我可以在if语句中使用任何类型的循环来解决这个问题吗PHP通过正则表达式匹配从文本生成超链接,php,function,loops,hyperlink,Php,Function,Loops,Hyperlink,我有一个脚本,使链接(http,https和www)在一个句子中可点击。问题是我只能有一个链接。我可以在if语句中使用任何类型的循环来解决这个问题吗 $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 htt
$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);
$text=“www.google.com和http://www.google.com/calendar/ 是链接”;
/**
*从文本中的URL创建可单击的链接。
*/
函数使_可点击($text){
//强制http到www。
$text=preg_replace(“(www\)”,”http://www.“,$text);
//强制后删除重复项。
$text=preg_replace(“(http://http://www\.)", "http://www.“,$text);
$text=preg_replace(“(https://http://www\.)", "https://www.“,$text);
//正则表达式。
$regExUrl=“/(http | https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/”;
//检查文本中是否有URL。
if(preg_匹配($regExUrl,$text,$url)){
//使URL成为超链接。
$text=preg\u replace(
$regExUrl,
'',
$text
);
}
返回$text;
}
echo可点击($text);
结果:
两者都是链接
提前感谢。您不需要任何循环。试试这个:
/**
* 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 are URLs in the text then replace all
$text = preg_replace_callback($regExUrl, function($matches) {
return '<a href="' . $matches[0] . '" target="_blank">' . $matches[0] . '</a>';
}, $text);
return $text;
}
/**
*从文本中的URL创建可单击的链接。
*/
函数使_可点击($text){
//强制http到www。
$text=preg_replace(“(www\)”,”http://www.“,$text);
//强制后删除重复项。
$text=preg_replace(“(http://http://www\.)", "http://www.“,$text);
$text=preg_replace(“(https://http://www\.)", "https://www.“,$text);
//正则表达式。
$regExUrl=“/(http | https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/”;
//检查文本中是否有URL,然后替换所有URL
$text=preg\u replace\u回调($regExUrl,function($matches){
返回“”;
}美元文本);
返回$text;
}
Ref:您到底有什么问题?这似乎像预期的那样工作…不,看看变量中的输入链接。输出只给我两个的第一个链接(两次)。如果输入是,我将得到两次。因此,我想我可能需要一个循环。明白了吗?你就是那个人,非常感谢!它工作得很好!:)