【问题标题】:replace URLs but not images using a regular expression使用正则表达式替换 URL 但不替换图像
【发布时间】: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:-: 符号之间。谁能帮帮我..?

【问题讨论】:

  • 您需要确定图像是什么使您能够将它们识别为图像(线索:扩展名),然后编写一个将忽略以这些扩展名结尾的任何文本字符串的正则表达式。我会删除:-:,因为它们并没有真正提供帮助。

标签: php regex


【解决方案1】:

你可以使用这个正则表达式:

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

RegEx Demo

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

【讨论】:

    【解决方案2】:

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

    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);
    

    【讨论】:

    • 这对我有用,我认为这是我工作的有效方式。
    • @Casperon:请注意,我的回答是一种更通用的方法,但对于您的具体情况,anubhava 回答可能更合适。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    相关资源
    最近更新 更多