2016-03-15 96 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,那我該怎麼辦? –