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.

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

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试