如何将纯文本链接/ URL转换为HTML(图像和链接)

时间:2017-03-15 15:54:14

标签: php html regex

所以我有一大串文字,可以包含网站或图片的链接。我想将这些普通的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" />?

请注意;

我发现了一些正则表达式示例执行两次转换之一(URL到href元素,或图像URL到标记,但我似乎无法找到合并它们的方法!:(

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;