我在网上找到了一个可以从纯文本中自动检测url的工作代码。我遇到的问题是,如果用户在纯文本中输入多个URL,就会创建一个数组来显示多个URL。也就是说,当他们在我的网站上发布帖子或评论时,假设他们有以下文本:
I found some really good articles on such and such topic. Here are a few links to check out:
http://www.example.com/hOSDHOUA and https://www.mywebsite.com/h/yIFeelLowIfImHigh and
http://example-site.com/today-is-a-beautiful-day/.
使用我现在拥有的代码...它将只显示第一个链接,并将其余链接输出为纯文本。我已经在网上搜索了过去7天,但找不到一个有效的答案。
我正在寻找的是如何将$url[0]
转换为一个数组,该数组自动将数组上的输出值增加1(取决于用户输入的链接量)。因此,在本例中,它应该显示为$url[0]
,然后下一个链接显示为$url[1]
,最后第三个链接显示为$url[2]
。但主要的关键是,我不希望显示一组(固定的)数组。相反,我正在寻找一个无限的数组输出或最大值,比如说200个限制。我之所以说是200,是因为它们的使用也将是一个SEE also类型的引用链接。
我的代码:(PHP)
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = $faq_seealso; // The variable $faq_seealso refers to my MySQL data fetch query.
// I will provide it if needed.
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, "<a href={$url[0]}>{$url[0]}</a> ", $text); // <--- Part in question
} else {
// if no urls in the text just return the text
echo $text;
}
?>
任何帮助都将不胜感激。
这是输出给我的代码:(来自我的网站的代码片段)
1. https://www.pokemongosrf.ca https://www.pokemongosrf.ca
1. https://www.pokemongosrf.ca http://kambel.ca
从第二行可以看到,作为两个单独链接输入的文本显示为两个链接,它们都与放置在Textfield中的第一个链接相同。我正在寻找他们被显示为自己独特的链接,而不是第一个链接的克隆。这里的任何帮助都将不胜感激。谢谢。
发布于 2018-12-07 03:08:04
我现在明白问题所在了。
使用preg_match_all匹配所有链接并循环它们。
在循环中,您执行一个简单的str_replace来将链接替换为html锚点。
$text ="I found some really good articles on such and such topic. Here are a few links to check out: http://www.example.com/hOSDHOUA and https://www.mywebsite.com/h/yIFeelLowIfImHigh and http://example-site.com/today-is-a-beautiful-day/. ";
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
// Check if there is a url in the text
if(preg_match_all($reg_exUrl, $text, $url)) {
foreach($url[0] as $link){
$text = str_replace($link, "<a href={$link}>{$link}</a> ", $text); // <--- Part in question
}
echo $text;
} else {
// if no urls in the text just return the text
echo $text;
}
//I found some really good articles on such and such topic. Here are a few links to check out: <a href=http://www.example.com/hOSDHOUA>http://www.example.com/hOSDHOUA</a> and <a href=https://www.mywebsite.com/h/yIFeelLowIfImHigh>https://www.mywebsite.com/h/yIFeelLowIfImHigh</a> and <a href=http://example-site.com/today-is-a-beautiful-day/.>http://example-site.com/today-is-a-beautiful-day/.</a>
发布于 2018-12-07 04:24:51
您应该在替换字符串中使用$0
来替换相应匹配的regexp。使用$url[0]
只从preg_match()
返回第一个匹配项。
echo preg_replace($reg_exUrl, "<a href=$0>$0</a> ", $text);
https://stackoverflow.com/questions/53657839
复制相似问题