【发布时间】:2014-10-25 10:02:48
【问题描述】:
我有一个这样的字符串:
$str = ':-:casperon.png:-: google.com www.yahoo.com :-:sample.jpg:-: http://stackoverflow.com';
我需要替换来自$str 的网址,而不是像casperon.png 这样的图像。
我已尝试使用以下正则表达式替换网址。
$regex = '/((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/';
$str = preg_replace_callback( $regex, 'replace_url', $str);
和下面的php函数。
function replace_url($m){
$link = $name = $m[0];
if ( empty( $m[1] ) ) {
$link = "http://".$link;
}
return '<a href="'.$link.'" target="_blank" rel="nofollow">'.$name.'</a>';
}
但是它将图像替换为链接。但我需要正常的图像。只有 url 需要替换。所以我把图像放在:-:image:-: 符号之间。谁能帮帮我..?
【问题讨论】:
-
您需要确定图像是什么使您能够将它们识别为图像(线索:扩展名),然后编写一个将忽略以这些扩展名结尾的任何文本字符串的正则表达式。我会删除
:-:,因为它们并没有真正提供帮助。