note 37349 modified in function.preg-replace-callback by cece

From: Date: Sun, 14 Nov 2004 16:05:52 +0000
Subject: note 37349 modified in function.preg-replace-callback by cece
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-80512@lists.php.net to get a copy of this message
You can use this function to display url address as a link or image based on suffix of the url. Every string beginning with www or http(s):// will be displayed as an URL address. But if the string ends with *.jpg or *.gif, it will be displayed as an image. Please note: This function also verifies the size of the image. If is it more than 600x400, it changes it. <?php $pattern_html = "/\b((http(s?):\/\/)|(www\.))([\w\.]+)"; $pattern_html .= "([\#\,\/\~\?\&\=\;\%\-\w+\.]+)\b/i"; $text = preg_replace_callback($pattern_html,'Check_if_Image',$text); . . function Check_if_Image($matches) { $suffix = strtolower(substr($matches[0],-4)); if ( $suffix == '.jpg' or $suffix == '.gif') { $dsn = 'http'.$matches[3].'://'.$matches[4].$matches[5]; if (list($width, $height, $type, $attr) = getimagesize("$dsn")) { if ( ($width > 600) ) { $koef = $width / 600; $width = 600; $height /= $koef; } if ( ($height > 400) ) { $koef = $height / 400; $height = 400; $width /= $koef; } } else { $height=400; $width=600; } $ret = "<img src=\"$dsn\""; $ret .= "\" border=0 width=\"$width\" height=\"$height\">"; } else { $ret = '<a href="http'.$matches[3].'://'.$matches[4].$matches[5]; $ret .='" target="_blank">'.$matches[0].'</a>'; } return ("$ret"); } ?> --was-- You can use this function to display url address as a link or image based on suffix of the url. Every string beginning with www or http(s):// will be displayed as an URL address. But if the string ends with *.jpg or *.gif, it will be displayed as an image. Please note: This function also verifies the size of the image. If is it more than 600x400, it changes it. <? $text = preg_replace_callback($pattern_html,'Check_if_Image',$text); . . function Check_if_Image($matches) { $suffix = strtolower(substr($matches[0],-4)); if ( $suffix == '.jpg' or $suffix == '.gif') { $dsn = 'http'.$matches[3].'://'.$matches[4].$matches[5]; if (list($width, $height, $type, $attr) = getimagesize("$dsn")) { if ( ($width > 600) ) { $koef = $width / 600; $width = 600; $height /= $koef; } if ( ($height > 400) ) { $koef = $height / 400; $height = 400; $width /= $koef; } } else { $height=400; $width=600; } $ret = "<img src=\"$dsn\""; $ret .= "\" border=0 width=\"$width\" height=\"$height\">"; } else { $ret = '<a href="http'.$matches[3].'://'.$matches[4].$matches[5]; $ret .='" target="_blank">'.$matches[0].'</a>'; } return ("$ret"); } ?> http://php.net/manual/en/function.preg-replace-callback.php

« previous php.notes (#80512) next »