PHP使用锚标记替换文本中的多个URL

时间:2016-03-15 09:00:11

标签: php regex

到目前为止,我试过了以下内容:

<?php

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

$text = "The text I want to filter is here. It has urls http://www.example.com and http://www.example.org";

// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {

       // make the urls hyper links
       $final = preg_replace($reg_exUrl, "<a href=\"{$url[0]}\">{$url[0]}</a> ", $text);

       echo $final;

} else {
       // if no urls in the text just return the text
       echo $text;
}

我面临的唯一问题是,这是用相同的网址(即首先找到的网址)替换网址。我如何loop这个用自己的网址替换每个网址?

2 个答案:

答案 0 :(得分:3)

只需使用一个preg_replace()

$url_regex = '~(http|ftp)s?://[a-z0-9.-]+\.[a-z]{2,3}(/\S*)?~i';

$text = 'The text I want to filter is here. It has urls https://www.example.com and http://www.example.org';

$output = preg_replace($url_regex, '<a href="$0">$0</a>', $text);

echo $output;

在替换部分中,您可以使用$0$1等来引用匹配的组...组0是整个匹配。

另一个例子:

$url_regex = '~(?:http|ftp)s?://(?:www\.)?([a-z0-9.-]+\.[a-z]{2,3}(?:/\S*)?)~i';

$text = 'Urls https://www.example.com and http://www.example.org or http://example.org';

$output = preg_replace($url_regex, '<a href="$0">$1</a>', $text);

echo $output;

// Urls <a href="https://www.example.com">example.com</a> and <a href="http://www.example.org">example.org</a> or <a href="http://example.org">example.org</a>

使用preg_match()没有意义,正则表达式调用的性能相对较高。

PS:我还在整个过程中调整了你的正则表达式。

答案 1 :(得分:2)

试试这个:

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

$text = "The text I want to filter is here. It has urls http://www.example.com and http://www.example.org";

// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {

    // make the urls hyper links
    $final = preg_replace($reg_exUrl, '<a href="$0">$0</a>', $text);

    echo $final;

} else {
    // if no urls in the text just return the text
    echo $text;
}

输出:

The text I want to filter is here. It has urls <a href="http://www.example.com">http://www.example.com</a> and <a href="http://www.example.org">http://www.example.org</a>