PHP find all links in the text

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

    i use this function

      <?php
        function deteli($string){
            $pos  = strpos($string, 'http');
            $spos = strpos($string, ' ', $pos);
            $lst  = $spos - $pos;
            $bef  = substr($string, 0, $pos);
            $aft  = substr($string, $spos);
            if ($pos == true || $pos == 0) {
                $link = substr($string, $pos, $lst);
                $res  =  $bef . "<a href='" . $link . "' class='link' target='_blank'>link</a>" . $aft . ""; 
                return  $res;
            }
            else{
                return $string;
            }
        }?>
    
    0 讨论(0)
  • 2021-02-16 00:37

    Alternative to regexp it´s use this library

    Works very good, butnot for very complex codes.

    foreach($html->find('a') as $element) 
           echo $element->href . '<br>';
    

    And easy to use. No regular expressions skills required:-)

    0 讨论(0)
提交回复
热议问题