PHP find all links in the text

后端 未结 8 1500
猫巷女王i
猫巷女王i 2021-02-15 23:36

I want to find all links in the text like this:

Test text http://hello.world Test text 
http://google.com/file.jpg Test text https://hell.o.wor.ld/test?qwe=qwe T         


        
8条回答
  •  有刺的猬
    2021-02-16 00:26

    I'd go with something simple like ~[a-z]+://\S+~i

    • starts with protocol [a-z]+://
    • \S+ followed by one or more non-whitespaces where \S is a shorthand for [^ \t\r\n\f]
    • used modifier i (PCRE_CASELESS) (possibly not really necessery)

    So it could look like this:

    $pattern = '~[a-z]+://\S+~';
    
    $str = 'Test text http://hello.world Test text 
    http://google.com/file.jpg Test text https://hell.o.wor.ld/test?qwe=qwe Test text 
    test text http://test.test/test';
    
    if($num_found = preg_match_all($pattern, $str, $out))
    {
      echo "FOUND ".$num_found." LINKS:\n";
      print_r($out[0]);
    }
    

    outputs:

    FOUND 4 LINKS:
    Array
    (
        [0] => http://hello.world
        [1] => http://google.com/file.jpg
        [2] => https://hell.o.wor.ld/test?qwe=qwe
        [3] => http://test.test/test
    )
    

    Test on eval.in

提交回复
热议问题