首页 > 解决方案 > 在纯文本中检测到的多个 URL 的自动增量数组

问题描述

我在网上找到了一个工作代码,用于从纯文本中自动检测 url。我遇到的问题是创建一个数组来显示多个 URL,如果用户将多个 URL 输入到纯文本中...... IE 当他们在我的网站上发布帖子或评论时,假设他们有以下文本:

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

从第二行可以看出,我作为 2 个单独链接输入的文本显示为 2 个链接,它们都与放置在文本字段中的第一个链接相同。我正在寻找将它们显示为自己的唯一链接,而不是第一个链接的克隆。在这里的任何帮助将不胜感激。谢谢你。

标签: php

解决方案


我现在看到了问题。

使用 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>  

https://3v4l.org/W4ifF


推荐阅读