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

标签 php regex

我有一个像这样的字符串:

$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.,@?^=%&amp;:/~+#-]*[\w@?^=%&amp;\/~+#-])?

RegEx Demo

此正则表达式的工作原理是首先选择 :-: 之间不需要的文本。和:-:并使用(*SKIP)(*F)丢弃它指令。

关于php - 使用正则表达式替换 URL,但不替换图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26561237/

相关文章:

PHP PDO 调用非对象上的成员函数 execute()

php - 上传的图片在数据库中存储了两次

php - 将 PHP 编译为操作码并执行操作码

regex - 正则表达式中单词的插入符/否定

php - Wordpress get_user_option() 开头

php - 如何只允许从我的 iOS 应用程序访问我的 MySQL 数据库? (使用 webapp 作为 db 的网关)

regex - 使用linux查找和替换

regex - 如何阻止对与 Apache 中常见模式匹配的 URL 的机器人请求?

javascript - 使用数组自定义对象

javascript - 使用正则表达式跨度包装 cout 的 "<<"的多次出现