使用正则表达式查找和替换 url 到 HTML 标记


Find & replace url to HTML tag using regular expression

我希望有一个可以在文本中解析的函数,然后它将用<img>标签替换所有包含(jpg|png|gif|jpeg|bmp)扩展名的链接,之后它还会将所有其他没有(jpg|png|gif|jpeg|bmp)扩展名的链接替换为<a>标签。

例如,它应该替换:

http://imgur.com/gallery/TpGvHBL http://i.imgur.com/TpGvHBL.jpg

<a href="http://imgur.com/gallery/TpGvHBL" target="_blank">http://imgur.com/gallery/TpGvHBL</a> <img src="http://i.imgur.com/TpGvHBL.jpg" />

====

====================================================================================

目前,我可以使用以下正则表达式将图像 url 替换为<img>标签:

$text = preg_replace('#((https?|ftp):'/'/([^'s]*)'.(jpg|gif|png))#', '<img src="$1" />', $text);

还有下面将普通网址替换为<a>标签:

$text = preg_replace('/('b(https?|ftp|file):'/'/[-A-Z0-9+&@#'/%?=~_|!:,.;]*[-A-Z0-9+&@#'/%=~_|])/i', '<a href="$1" target="_blank">$1</a>', $text);

想要的是更改第二个正则表达式以仅替换非图像 url,因为它将与我的第一个正则表达式冲突。

谢谢。

抱歉回复晚了,我将即时回答。

所以这是我想出的解决方案:

$string = 'some test http://imgur.com/gallery/TpGvHBL http://i.imgur.com/TpGvHBL.jpg something else ...';
$result = preg_replace_callback('~'b(?:https?|ftp|file)://'S+~i', function($v){
    if(preg_match('~'.jpe?g|'.png|'.gif|'.bmp$~i', $v[0])){ // if image
        return '<img src="' . $v[0] . '">';
    }else{
        return '<a href="' . $v[0] . '" target="_blank">' . $v[0] . '</a>';
    }
}, $string);

我想匹配所有网址,然后检查是否有图像扩展名。当然,第一个正则表达式非常松散,您可能会对其进行改进......请注意,您需要 PHP 5.3+,因为我使用的是匿名函数。

正则表达式解释:

~                   # delimiter
    'b              # word boundary
    (?:             # start of a non-capturing group
        https?      # match http or https
        |           # or
        ftp         # match ftp (you may want to add sftp o_O ?)
        |           # or
        file        # match file
    )               # end of the non-capturing group
    ://             # match ://
    'S+             # match anything except whitespace one or more times
~                   # delimiter, end of expression
i                   # set the i modifier : match case-insensitive

第二个正则表达式~'.jpe?g|'.png|'.gif|'.bmp$~i仅匹配字符串末尾jpg, jpeg, png, gif and bmp的以下扩展名。

我希望这就是你要找的

解决方案 1:

<?php
$str="http://imgur.com/gallery/TpGvHBL http://i.imgur.com/TpGvHBL.jpg";
$new_str=explode(" ",$str);
$str="<a href=".$new_str[0]." target=_blank>".$new_str[0]."</a>";
$str.=" <img src=".$new_str[1]." />";
echo htmlentities($str);

输出:

<a href=http://imgur.com/gallery/TpGvHBL target=_blank>http://imgur.com/gallery/TpGvHBL</a> <img src=http://i.imgur.com/TpGvHBL.jpg />

解决方案 2:

<?php
//$str='http://imgur.com/gallery/TpGvHBL';
$str='http://i.imgur.com/TpGvHBL.jpg';
if(is_array(getimagesize($str)))
{
echo "Image<br>";
    $str="<img src=".$str." />";
}
else
{
    echo "Link<br>";
    $str="<a href=".$str." target=_blank>".$str."</a>";
}
echo htmlentities($str);

输出:

Image
http://i.imgur.com/TpGvHBL.jpg

@hamza的正则表达式会遗漏一些不能属于URL的符号,例如引号,括号等。

我建议改变这一点:

~'b(?:https?|ftp|file)://'S+~i

对此:

~'b(?:https?|ftp|file):'/'/[^'s"'(){}<>|''^~`]+~i