duanjia1870 2015-11-05 02:39 采纳率: 0%
浏览 46
已采纳

PHP - 使用链接或图像替换文本中的URL

Doesn't matter how much I try, I can't figure this out. I have a comments section on my website and I have some functions using regex expressions. One of mine functions replaces URLs in the content string in links, as long as it can, it is working pretty well. But I wanted to check if the match is a normal link or if it is an image (ends with .jpg, .gif, etc) if so, it should then have the replace expression with <img> tags. What I have so for:

function url_parse($string) {
    $string = preg_replace('/\b(?:(http(s?):\/\/)|(?=www\.))(\S+)/is', '<a href="http$2://$3" target="_blank">$1$3</a>', $string);
    return $string; 
}

This one is the function to replace the links. Easy as that. But my idea to check if it is a image, I made alot of confusions here. I don't even know how to extact the link, so I do this:

function geturl($string) {
    $regex = '/\b(?:(http(s?):\/\/)|(?=www\.))(\S+)/is';
    preg_match_all($regex, $string, $matches);
    return ($matches[0]);
}

I even made a function to check if it is actually a link to a image

function isIMG($url){
    $ext = strrpos( $url, ".");
    if ($pos === false) {
        return false;
    }
    $ext = strtolower(trim(substr( $url, $pos)));
    $exts = array(".gif", ".jpg", ".jpeg", ".png", ".tiff", ".tif");
    if (in_array($ext, $exts)) {
        return true;
    }
    else {
       return false;
    }
}

But, I got myself into a LIMBO. I just can't put it all working together. I tried everything... Any help?

The objective here is:

  1. Check if the URL extracted from the string is a normal link OR if it have an image ext.

  2. preg_replace in the string. I hope that this question doesn't seem messed up. Really needing any help here.

  • 写回答

1条回答 默认 最新

  • dtwxmn8741 2015-11-05 03:20
    关注

    You can use this regex, with insensitive case:

    \.(?:gif|jpe?g|tiff?|png)$
    

    Regex live here.

    And, if there is a match againt $url then it is one of your images.

    Hope it helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器