使用正则表达式替换URL,但不替换图像


replace URLs but not images using a regular expression

我有一个这样的字符串:

$str = ':-:casperon.png:-: google.com www.yahoo.com :-:sample.jpg:-: http://stackoverflow.com';

并且我需要替换来自$str的url,但不需要像casperon.png这样的图像。

我尝试了以下正则表达式来替换url。

$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:-:符号之间。有人能帮我吗。。?

您可以使用以下正则表达式:

:-:.*?:-:'W*(*SKIP)(*F)|(?:(?:http|ftp|https)://)?['w-]+(?:'.['w-]+)+(['w.,@?^=%&amp;:/~+#-]*['w@?^=%&amp;'/~+#-])?

RegEx演示

此正则表达式的工作原理是首先在:-::-:之间选择不需要的文本,然后使用(*SKIP)(*F)指令将其丢弃

您可以这样更改代码,使用filter_var检查可能的url:

function replace_url($m){
    $link = (empty($m[1])) ? 'http://' . $m[0] : $m[0];
    if (!filter_var($link, FILTER_VALIDATE_URL))
        return $m[0];
    return '<a href="' . $link . '" target="_blank" rel="nofollow">' . $m[0] . '</a>';
}

$regex  = '~((?:https?|ftp)://)?['w-]+(?>'.['w-]+)+(?>[.,]*(?>['w@?^=%/'~+#;-]+|&(?:amp;)?)+)*~';
$str =  preg_replace_callback( $regex, 'replace_url', $str);