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.

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

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备