Replace URLs in text with HTML links

后端 未结 17 2074
栀梦
栀梦 2020-11-22 11:27

Here is a design though: For example is I put a link such as

http://example.com

in textarea. How do I get PHP t

17条回答
  •  再見小時候
    2020-11-22 11:45

    This class I created works for my needs, admittedly it does needs some work though;

    class addLink
    {
        public function link($string)
        {
            $expression = "/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,63}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/";
            if(preg_match_all($expression, $string, $matches) == 1)// If the pattern is found then
            {
                $string = preg_replace($expression, '$1', $string);
            }
    
            return $string;       
        }
    }
    

    An example of using this code;

    include 'PHP/addLink.php';
    
    if(class_exists('addLink')) 
    {                  
        $al = new addLink();                  
    }
    else{
        echo 'Class not found...';
    } 
    
    $paragraph = $al->link($paragraph);
    

提交回复
热议问题