php: Remove URL from string

后端 未结 2 1667
走了就别回头了
走了就别回头了 2021-02-14 14:58

I have many strings (twitter tweets) from which I would like to remove the links when I echo them .

I have no control over the string and even though all the links star

相关标签:
2条回答
  • 2021-02-14 15:18

    If you want to remove everything, link and after the link, like via thing in your example, the below may help you:

    $string = "The Third Culture: The Frontline of Global Thinkinghttp://is.gd/qFioda;via @edge";
    $regex = "@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?).*$)@";
    echo preg_replace($regex, ' ', $string);
    

    If you want to keep them:

    $string = "The Third Culture: The Frontline of Global Thinkinghttp://is.gd/qFioda;via @edge";
    $regex = "@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@";
    echo preg_replace($regex, ' ', $string);
    
    0 讨论(0)
  • 2021-02-14 15:25

    I would do something like this:

    $input = "The Third Culture: The Frontline of Global Thinkinghttp://is.gd/qFioda;via @edge";
    $replace = '"(https?://.*)(?=;)"';
    
    $output = preg_replace($replace, '', $input);
    print_r($output);
    

    It works for multiple occurances too:

    $output = preg_replace($replace, '', $input."\n".$input);
    print_r($output);
    
    0 讨论(0)
提交回复
热议问题