doulu1544 2017-03-21 01:03
浏览 97
已采纳

PHP正则表达式将纯文本URL转换为链接,除非它已经存在

I have a php string $tweet that looks like this...

This is a sample tweet https://tr.co/sdfhnjn3

But sometimes it can look like this...

This is a sample tweet <a href="https://tr.co/sdfhnjn3">https://tr.co/sdfhnjn3</a>

I am wanting to convert all https://tr.co links to actual a href links unless they are already in that format.

I know I can convert the links with Regex but can I also check if they are already a link using it as well?

  • 写回答

3条回答 默认 最新

  • doufan2541 2018-11-16 23:04
    关注

    Without going into incredibly sophisticated syntax trying to match bits and pieces of a url, you can disqualify already-tagged urls using (*SKIP)(*FAIL) and then only match the urls from your domain.

    Code: (Demo) (Regex101)

    $tweets = [
        'This is a sample tweet https://tr.co/sdfhnjn3',
        'This is a sample tweet <a href="https://tr.co/sdfhnjn3">https://tr.co/sdfhnjn3</a>',
        'This is a sample tweet https://example.com/sdfhnjn3',
        'This is a sample tweet <a href="https://example.com/sdfhnjn3">https://example.com/sdfhnjn3</a>'
    ];
    
    var_export(preg_replace('~<a [^>]+>.*?</a>(*SKIP)(*FAIL)|https?://(?:www)?tr.co/\S*~', '<a href="$0">$0</a>', $tweets));
    

    Output:

    array (
      0 => 'This is a sample tweet <a href="https://tr.co/sdfhnjn3">https://tr.co/sdfhnjn3</a>',
      1 => 'This is a sample tweet <a href="https://tr.co/sdfhnjn3">https://tr.co/sdfhnjn3</a>',
      2 => 'This is a sample tweet https://example.com/sdfhnjn3',
      3 => 'This is a sample tweet <a href="https://example.com/sdfhnjn3">https://example.com/sdfhnjn3</a>',
    )
    

    *only the first element was actually updated, the others did not qualify.

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

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等