2016-03-15 34 views
1

我已经试过到目前为止以下:PHP替换多个URL的文本与锚标记

<?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; 
} 

我现在面临的唯一问题是,这是用相同的URL替换URL都的(也就是一个发现第一)。我如何loop这个用自己替换每个url?

回答

2

只需使用单一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:我也一直在调整你的正则表达式。

+0

太棒了。谢谢@HamZa –

+0

@RipHunter请参阅编辑。没有必要使用'preg_match()'。 – HamZa

+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> 
+0

只是我一直在寻找的东西!谢谢 –

+0

如果我想urlencode $ 0,那我该怎么办? –