【问题标题】:How do I convert plain text links/URL's to HTML (images AND links)如何将纯文本链接/URL 转换为 HTML(图像和链接)
【发布时间】:2017-03-15 15:54:13
【问题描述】:

所以我有一大串文本,其中可以包含指向网站或图像的链接。我想将这些纯 URL 转换为 html 元素。

示例输入:

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?

需要的输出:

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" />?

注意;

我发现了一些正则表达式示例,它们执行两种转换之一(URL 到 href 元素,或图像 URL 到标记,但我似乎无法找到组合它们的方法!:(

【问题讨论】:

    标签: php html regex


    【解决方案1】:

    您可以通过以下方式完成此操作...

    $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

    【讨论】:

      【解决方案2】:

      使用 preg_replace sandbox.onlinephpfunctions.com

      $count = null;
      $string = "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?";
      $string = preg_replace('~https?://(?![^" ]*(?:jpg|png|gif))[^" ]+\w~', '<a href="$0" target="_blank" title="$0">$0</a>', '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?', -1, $count);
      $string = preg_replace('~([a-z\\-_0-9\\/\\:\\.]*\\.(jpg|jpeg|png|gif)).~', '<img src="$0" />', $string, -1, $count);
      print $string;
      

      【讨论】:

      • 这会将所有 URL 转换为链接 (href),但不会将图像链接转换为 标记。
      猜你喜欢
      • 1970-01-01
      • 2010-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      相关资源
      最近更新 更多