douxiajia6104 2017-03-15 15:54
浏览 54
已采纳

如何将纯文本链接/ URL转换为HTML(图像和链接)

So I have a large string of text that can contain links to websites or images. I want to convert these plain URL's to html elements.

Example input:

Hi my name is Harry you can find my website here: http://www.harry-rox.com. Oh and what do you think of my my wife: http://www.anothersite.com/wife.jpg?

Needed output:

Hi my name is Harry you can find my website here: <a href="http://www.harry-rox.com">http://www.harry-rox.com</a>. Oh and what do you think of my my wife: <img src="http://www.anothersite.com/wife.jpg" />?

Note;

I found some regex examples that do one of both conversions (URL to href element, or image URL to tag, but I can't seem to find way to combine them! :(

  • 写回答

2条回答 默认 最新

  • duanjiebian6712 2017-03-15 16:38
    关注

    You could accomplish this in the following way ...

    $str = 'Hi my name is Harry you can find my website here: http://www.harry-rox.com. Oh and what do you think of my my wife: http://www.anothersite.com/wife.jpg?';
    $r1 = '/(http:\/\/[\S]+(?:jpg|jpeg|png|gif))/';
    $r2 = '/(?<!src=")(http:\/\/[\S]+\b)/';
    $sub1 = '<img src="$1"/>';
    $sub2 = '<a href="$1">$1</a>';
    $res = preg_replace($r1, $sub1, $str);
    $result = preg_replace($r2, $sub2, $res);
    echo $result;
    

    DEMO

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛