PHP find all links in the text

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

    function turnUrlIntoHyperlink($string){
        //The Regular Expression filter
        $reg_exUrl = "/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/";
    
        // Check if there is a url in the text
        if(preg_match_all($reg_exUrl, $string, $url)) {
    
            // Loop through all matches
            foreach($url[0] as $newLinks){
                if(strstr( $newLinks, ":" ) === false){
                    $link = 'http://'.$newLinks;
                }else{
                    $link = $newLinks;
                }
    
                // Create Search and Replace strings
                $search  = $newLinks;
                $replace = ''.$link.'';
                $string = str_replace($search, $replace, $string);
            }
        }
    
        //Return result
        return $string;
    }
    

提交回复
热议问题