我有一个像这样的字符串:
$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>';
}
但它替换了图像作为链接。但我需要像平常一样的图像。只需要替换网址。所以我将图像放在 :-:image:-:
符号之间。谁能帮助我..?
最佳答案
您可以使用此正则表达式:
:-:.*?:-:\W*(*SKIP)(*F)|(?:(?:http|ftp|https)://)?[\w-]+(?:\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&\/~+#-])?
RegEx Demo
此正则表达式的工作原理是首先选择 :-:
之间不需要的文本。和:-:
并使用(*SKIP)(*F)
丢弃它指令。
关于php - 使用正则表达式替换 URL,但不替换图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26561237/