Extract URLs from text in PHP

后端 未结 14 2088
野趣味
野趣味 2020-11-22 13:29

I have this text:

$string = \"this is my friend\'s website http://example.com I think it is coll\";

How can I extract the link into another

相关标签:
14条回答
  • 2020-11-22 14:00
    preg_match_all('/[a-z]+:\/\/\S+/', $string, $matches);
    

    This is an easy way that'd work for a lot of cases, not all. All the matches are put in $matches. Note that this do not cover links in anchor elements (<a href=""...), but that wasn't in your example either.

    0 讨论(0)
  • 2020-11-22 14:01
    public function find_links($post_content){
        $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
        // Check if there is a url in the text
        if(preg_match_all($reg_exUrl, $post_content, $urls)) {
            // make the urls hyper links,
            foreach($urls[0] as $url){
                $post_content = str_replace($url, '<a href="'.$url.'" rel="nofollow"> LINK </a>', $post_content);
            }
            //var_dump($post_content);die(); //uncomment to see result
            //return text with hyper links
            return $post_content;
        } else {
            // if no urls in the text just return the text
            return $post_content; 
        }
    }
    
    0 讨论(0)
提交回复
热议问题