Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从一堆字符串创建url链接_Php_Regex - Fatal编程技术网

Php 从一堆字符串创建url链接

Php 从一堆字符串创建url链接,php,regex,Php,Regex,我有一堆字符串连接在一起,形成一个包含文本和链接的字符串。我想在字符串中查找URL,并想将href放到每个URL中(创建链接)。我使用正则表达式模式查找字符串中的URL(链接)。请查看下面的示例: 例如: <?php // The Text you want to filter for urls $text = "The text you want to filter goes here. http://google.com/abc/pqr 2The text y

我有一堆字符串连接在一起,形成一个包含文本和链接的字符串。我想在字符串中查找URL,并想将
href
放到每个URL中(创建链接)。我使用正则表达式模式查找字符串中的URL(链接)。请查看下面的示例:

例如:

    <?php

// The Text you want to filter for urls
        $text = "The text you want to filter goes here. http://google.com/abc/pqr
2The text you want to filter goes here. http://google.in/abc/pqr
3The text you want to filter goes here. http://google.org/abc/pqr
4The text you want to filter goes here. http://www.google.de/abc/pqr";

// The Regular Expression filter
        $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";


// 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);
        } else {
            // if no urls in the text just return the text
            echo $text . "<br/>";
        }
        ?>

这有什么问题

由于正则表达式是用斜杠分隔的,所以当正则表达式包含斜杠时需要非常小心。通常,使用不同的字符来分隔正则表达式更容易:PHP并不介意您使用什么

尝试将第一个和最后一个“/”字符替换为另一个字符,例如“#”,您的代码可能会正常工作

您还可以简化代码,通过调用preg_replace完成整个过程,如下所示:

<?php

$text = 'The text you want to filter goes here. http://google.com/abc/pqr
    2The text you want to filter goes here. http://google.in/abc/pqr
    3The text you want to filter goes here. http://google.org/abc/pqr
    4The text you want to filter goes here. http://www.google.de/abc/pqr';

echo preg_replace('#(http|https|ftp|ftps)\://[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(/\S*)?#i', '<a href="$0">$0</a>', $text);

如果不使用占位符语法,请使用
preg\u replace\u callback
。还有现有的“linkify”工具。在博客帖子中的解决方案评论中有更多的解决方案本身也不起作用。
<?php

$text = 'The text you want to filter goes here. http://google.com/abc/pqr
    2The text you want to filter goes here. http://google.in/abc/pqr
    3The text you want to filter goes here. http://google.org/abc/pqr
    4The text you want to filter goes here. http://www.google.de/abc/pqr';

echo preg_replace('#(http|https|ftp|ftps)\://[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(/\S*)?#i', '<a href="$0">$0</a>', $text);