【问题标题】:Expression to Remove Last URL link from Text in PHP [duplicate]从 PHP 中的文本中删除最后一个 URL 链接的表达式 [重复]
【发布时间】:2019-05-09 00:25:55
【问题描述】:

我想删除字符串中最后出现的网址

输入

嘿,一切顺利。 https://google.com/last

输出

大家好。

输入

感谢您让我接触 300 万。 https://google.com/first。这不是我的成就……这是你的爱。 https://google.com/second。永远感恩https://google.com/last

输出

感谢您让我接触 300 万。 https://google.com/first。这不是我的成就……这是你的爱。 https://google.com/second。永远的感恩

【问题讨论】:

    标签: php regex string


    【解决方案1】:

    你可以试试下面的代码。

    $str = "Thank you for making me touch 3 Million. https://google.com/first. It’s not MY achievement... it’s your LOVE. https://google.com/second. Gratitude forever https://google.com/last";
    //$str = "Hey All the Best. https://google.com/last";
    $p = "/(https?:\/\/[^\/]+(?:[\d\w\/\._]*)\s*)$/i";
    $result = preg_replace($p, '', $str);
    var_dump($result);
    

    正则表达式中的'$'是最后一个匹配,如果不加'$',所有的链接都会被匹配出去。对应这个是'^',匹配开头。

    【讨论】:

    • 虽然这可能会回答这个问题,但您应该 edit 您的回答包括一些关于其工作原理的解释。代码块本身不会立即对以后可能遇到相同问题的人有用。
    • 感谢您的提醒。 @Hoppeduppeanut
    【解决方案2】:

    这样就可以了:

    https?://\S+(?!.*https?://\S+)
    

    【讨论】:

      猜你喜欢
      • 2014-08-15
      • 2019-12-19
      • 2010-10-23
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 2010-10-23
      相关资源
      最近更新 更多