MySQL Forums
Forum List  »  PHP

Re: Echo URL as hot link
Posted by: Peter Brawley
Date: December 17, 2020 10:57AM

How TheUsual does it ...

/*
 * urlactivate( $txt, &$found, $reg_exUrl ) 
 * surround urls in txt with href or img html code
 */
function urlactivate ( 
    $text, 
    &$found, 
    $reg_exUrl="/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"
  ) {
  // PREPEND https:// TO BARE www.
  $text = preg_replace( "#(?<!://)www.#", "https://www.";, $text);
  preg_match_all( $reg_exUrl, $text, $matches );
  $usedUrls = array();
  foreach( $matches[0] as $url ) {
    if( !array_key_exists( $url, $usedUrls ) ) {
      $found = TRUE;
      $usedUrls[$url] = true;
      if( isImage($url) ) {
        $text = str_replace( $url, '<img src="'.$url.'">', $text );
      }
      else {
        $offset=0;
        while( ($p=stripos($text,$url,$offset)) !== FALSE ) {
          $s = strtolower( substr($text,$p-9,9) );
          if( $s != "<a href='" && $s != '<a href="' ) {
            $text = substr_replace( $text, 
                                    '<a target=\"_blank\" href="'.$url.'">'.$url.'</a>', 
                                    $p, 
                                    strlen($url) 
                                  );
            $offset += $p + ( 2 * strlen($url) ) + 14;
          }
          else $offset += $p + strlen($url);
          if( $offset >= strlen($txt) ) break;
        }
        $text = str_replace( "<a href=", "<a target='_blank' href=", $text );
      }
    }
  }
  return $text;
}

function isImage( $url ) {
  return stripos( "|.gif|.jpg|.png|.tif|.bmp|.ico|", substr($url,-4) ) 
      || stripos( "|.jpeg|.tiff|", substr($url,-5) );
}

Options: ReplyQuote


Subject
Written By
Posted
December 17, 2020 04:44AM
Re: Echo URL as hot link
December 17, 2020 10:57AM
December 18, 2020 05:51AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.