PHP find all links in the text

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

    Not regexp, but finds it all and makes sure that they are not already encompassed in a tag already. It also checks to make sure that the link isn't encapsulated in (), [], "" or anything else with an open and close.

    $txt = "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 I am already linked up
    It was also done in 1927 (http://test.com/reference) Also check this out:http://test/index&t=27";
    $holder = explode("http",$txt);
    for($i = 1; $i < (count($holder));$i++) {
        if (substr($holder[$i-1],-6) != 'href="') { // this means that the link is not alread in an a tag.
            if (strpos($holder[$i]," ")!==false) //if the link is not the last item in the text block, stop at the first space
                $href = substr($holder[$i],0,strpos($holder[$i]," "));
            else                                //else it is the last item, take it
                $href = $holder[$i];
            if (ctype_punct(substr($holder[$i-1],strlen($holder[$i-1])-1)) && ctype_punct(substr($holder[$i],strlen($holder[$i])-1)))
                $href = substr($href,0,-1);     //if both the fron and back of the link are encapsulated in punctuation, truncate the link by one
            $holder[$i] = implode("$href\" target=\"_blank\" class=\"link\">http$href",explode($href,$holder[$i]));
            $holder[$i-1] .= "

    Output:

    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 I am already linked up
    It was also done in 1927 (http://test.com/reference) Also check this out:http://test/index&t=27
    

提交回复
热议问题