PHP find all links in the text

后端 未结 8 1506
猫巷女王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:17

    The suggested answers are great, but one of them miss www. case, the other http://

    So, let's combine all of those:

    $text = 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
    
    preg_match_all('/(((http|https|ftp|ftps)\:\/\/)|(www\.))[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\:[0-9]+)?(\/\S*)?/', $text, $results, PREG_PATTERN_ORDER);
    
    print_r($results[0]);
    

    The return value for PREG_PATTERN_ORDER will be Array of Arrays (results) so that $results[0] is an array of full pattern matches, $results[1] is an array of strings matched by the first parenthesized subpattern, and so on.

提交回复
热议问题