2017-03-15 11 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、または画像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

すべてのURLをリンク(href)に変換しますが、タグへの画像リンクは変換しません。 – avroo

+0

あなたの編集した質問と一致する訂正された答え。 – BioGenX

関連する問題