2017-03-15 89 views
-1

因此,我有一大串文字可以包含指向網站或圖像的鏈接。我想將這些普通的URL轉換爲html元素。如何將純文本鏈接/ URL轉換爲HTML(圖像和鏈接)

示例輸入:

Hi my name is Harry you can find my website here: http://www.harry-rox.com. Oh and what do you think of my my wife: http://www.anothersite.com/wife.jpg? 

所需輸出:

Hi my name is Harry you can find my website here: <a href="http://www.harry-rox.com">http://www.harry-rox.com</a>. Oh and what do you think of my my wife: <img src="http://www.anothersite.com/wife.jpg" />? 

注;

我發現做這兩次轉換的一個(網址HREF元素,或圖像URL標記一些正則表達式的例子,但我似乎無法找到辦法把它們結合起來!:(

回答

1

您可以通過以下方式做到這一點...

$str = 'Hi my name is Harry you can find my website here: http://www.harry-rox.com. Oh and what do you think of my my wife: http://www.anothersite.com/wife.jpg?'; 
$r1 = '/(http:\/\/[\S]+(?:jpg|jpeg|png|gif))/'; 
$r2 = '/(?<!src=")(http:\/\/[\S]+\b)/'; 
$sub1 = '<img src="$1"/>'; 
$sub2 = '<a href="$1">$1</a>'; 
$res = preg_replace($r1, $sub1, $str); 
$result = preg_replace($r2, $sub2, $res); 
echo $result; 

DEMO

0

使用的preg_replace sandbox.onlinephpfunctions.com

$count = null; 
$string = "Hi my name is Harry you can find my website here: http://www.harry-rox.com. Oh and what do you think of my my wife: http://www.anothersite.com/wife.jpg?"; 
$string = preg_replace('~https?://(?![^" ]*(?:jpg|png|gif))[^" ]+\w~', '<a href="$0" target="_blank" title="$0">$0</a>', 'Hi my name is Harry you can find my website here: http://www.harry-rox.com. Oh and what do you think of my my wife: http://www.anothersite.com/wife.jpg?', -1, $count); 
$string = preg_replace('~([a-z\\-_0-9\\/\\:\\.]*\\.(jpg|jpeg|png|gif)).~', '<img src="$0" />', $string, -1, $count); 
print $string; 
+0

這會將所有網址轉換爲鏈接(href),但不會將圖片鏈接轉換爲標記。 – avroo

+0

更正的答案符合您編輯的問題。 – BioGenX