$string = 'Получаю только https://test.com/list?list=LLYRGq_jXSq6b3_BA текст а не ссылки http://veg.net/?pomidor=ogurec%131%ea%f в тексте. И все равно не то'; $pattern = '/https?.*\s/u'; echo preg_replace($pattern, "" ,$string); 

In general, in this mask I try to select links from http (s) to the first following space, but, unfortunately, the selection is too much. How to actually capture only the link and the first space after it?

    4 answers 4

    Unfortunately, too many seized sampling.

    To solve this problem, after the asterisk you need to put a question mark. This will limit the greed of the character class and it will search for the first space, not the last.

    But to make a more or less universal solution,

     '~(ftp|http)s?://\S+~ui'; 

      Try the following regulars, usually using it for a URL:

       (http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)? 

      Then your code is:

       $string = 'Получаю только https://test.com/list?list=LLYRGq_jXSq6b3_BA текст а не ссылки http://veg.net/?pomidor=ogurec%131%ea%f в тексте. И все равно не то'; $pattern = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/'; echo preg_replace($pattern, "" ,$string); 

      Displays the following:

      I receive only the text and not links in the text. And still not

      • is 10 years out of date - Ipatiev
      • Again, idiots, well-wishers encourage govnokod. enough already? - Ipatiev

      Try $ pattern = "https: // \ S * \ s" enter image description here

        For your task, this is enough:

         [az]+[:.].*?(?=\s) 

        Result:

         Match 1 Full match 15-59 `https://test.com/list?list=LLYRGq_jXSq6b3_BA` Match 2 Full match 78-121 `http://www.veg.net/?pomidor=ogurec%131%ea%f` 
        • And if the link is at the end of the line? Well, that is, there is no space after it - Wayer
        • Then it will not work. You set the task "until the first following space". - Hombre
        • @Wayer, so you have the same thing. What kind of manner, first write one question, then make a complaint that you did not answer the other? - Ipatiev
        • @ Ipatiev I just clarified, I changed my main question. - Wayer