分享經(jīng)常用到的21個(gè)PHP函數(shù)代碼段(下)
下面介紹的是,在PHP開發(fā)中,經(jīng)常用到的21個(gè)函數(shù)代碼段,當(dāng)我們用到的時(shí)候,就可以直接用了。
接上一篇,分享經(jīng)常用到的21個(gè)PHP函數(shù)代碼段(上)
12. PHP創(chuàng)建標(biāo)簽云
- function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 )
 - {
 - $minimumCount = min( array_values( $data ) );
 - $maximumCount = max( array_values( $data ) );
 - $spread = $maximumCount – $minimumCount;
 - $cloudHTML = ”;
 - $cloudTags = array();
 - $spread == 0 && $spread = 1;
 - foreach( $data as $tag => $count )
 - {
 - $size = $minFontSize + ( $count – $minimumCount )
 - * ( $maxFontSize – $minFontSize ) / $spread;
 - $cloudTags[] = ‘<a style=”font-size: ‘ . floor( $size ) . ‘px’
 - . ‘” href=”#” title=”\” . $tag .
 - ‘\’ returned a count of ‘ . $count . ‘”>’
 - . htmlspecialchars( stripslashes( $tag ) ) . ‘</a>’;
 - }
 - return join( “\n”, $cloudTags ) . “\n”;
 - }
 - /**************************
 - **** Sample usage ***/
 - $arr = Array(‘Actionscript’ => 35, ‘Adobe’ => 22, ‘Array’ => 44, ‘Background’ => 43,
 - ‘Blur’ => 18, ‘Canvas’ => 33, ‘Class’ => 15, ‘Color Palette’ => 11, ‘Crop’ => 42,
 - ‘Delimiter’ => 13, ‘Depth’ => 34, ‘Design’ => 8, ‘Encode’ => 12, ‘Encryption’ => 30,
 - ‘Extract’ => 28, ‘Filters’ => 42);
 - echo getCloud($arr, 12, 36);
 
13. PHP尋找兩個(gè)字符串的相似性
PHP 提供了一個(gè)極少使用的 similar_text 函數(shù),但此函數(shù)非常有用,用于比較兩個(gè)字符串并返回相似程度的百分比。
- similar_text($string1, $string2, $percent);
 - //$percent will have the percentage of similarity
 
14. PHP在應(yīng)用程序中使用 Gravatar 通用頭像
隨著 WordPress 越來越普及,Gravatar 也隨之流行。由于 Gravatar 提供了易于使用的 API,將其納入應(yīng)用程序也變得十分方便。
- /******************
 - *@email – Email address to show gravatar for
 - *@size – size of gravatar
 - *@default – URL of default gravatar to use
 - *@rating – rating of Gravatar(G, PG, R, X)
 - */
 - function show_gravatar($email, $size, $default, $rating)
 - {
 - echo ‘<img src=”http://www.gravatar.com/avatar.php?gravatar_id=’.md5($email).
 - ‘&default=’.$default.’&size=’.$size.’&rating=’.$rating.’” width=”‘.$size.’px”
 - height=”‘.$size.’px” />’;
 - }
 
15. PHP在字符斷點(diǎn)處截?cái)辔淖?/strong>
所謂斷字 (word break),即一個(gè)單詞可在轉(zhuǎn)行時(shí)斷開的地方。這一函數(shù)將在斷字處截?cái)嘧址?/p>
- // Original PHP code by Chirp Internet: www.chirp.com.au
 - // Please acknowledge use of this code by including this header.
 - function myTruncate($string, $limit, $break=”.”, $pad=”…”) {
 - // return with no change if string is shorter than $limit
 - if(strlen($string) <= $limit)
 - return $string;
 - // is $break present between $limit and the end of the string?
 - if(false !== ($breakpoint = strpos($string, $break, $limit))) {
 - if($breakpoint < strlen($string) – 1) {
 - $string = substr($string, 0, $breakpoint) . $pad;
 - }
 - }
 - return $string;
 - }
 - /***** Example ****/
 - $short_string=myTruncate($long_string, 100, ‘ ‘);
 
16. PHP文件 Zip 壓縮
- /* creates a compressed zip file */
 - function create_zip($files = array(),$destination = ”,$overwrite = false) {
 - //if the zip file already exists and overwrite is false, return false
 - if(file_exists($destination) && !$overwrite) { return false; }
 - //vars
 - $valid_files = array();
 - //if files were passed in…
 - if(is_array($files)) {
 - //cycle through each file
 - foreach($files as $file) {
 - //make sure the file exists
 - if(file_exists($file)) {
 - $valid_files[] = $file;
 - }
 - }
 - }
 - //if we have good files…
 - if(count($valid_files)) {
 - //create the archive
 - $zip = new ZipArchive();
 - if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
 - return false;
 - }
 - //add the files
 - foreach($valid_files as $file) {
 - $zip->addFile($file,$file);
 - }
 - //debug
 - //echo ‘The zip archive contains ‘,$zip->numFiles,’ files with a status of ‘,$zip->status;
 - //close the zip — done!
 - $zip->close();
 - //check to make sure the file exists
 - return file_exists($destination);
 - }
 - else
 - {
 - return false;
 - }
 - }
 - /***** Example Usage ***/
 - $files=array(‘file1.jpg’, ‘file2.jpg’, ‘file3.gif’);
 - create_zip($files, ‘myzipfile.zip’, true);
 
#p#
17. PHP解壓縮 Zip 文件
- /**********************
 - *@file – path to zip file
 - *@destination – destination directory for unzipped files
 - */
 - function unzip_file($file, $destination){
 - // create object
 - $zip = new ZipArchive() ;
 - // open archive
 - if ($zip->open($file) !== TRUE) {
 - die (’Could not open archive’);
 - }
 - // extract contents to destination directory
 - $zip->extractTo($destination);
 - // close archive
 - $zip->close();
 - echo ‘Archive extracted to directory’;
 - }
 
18. PHP為 URL 地址預(yù)設(shè) http 字符串
有時(shí)需要接受一些表單中的網(wǎng)址輸入,但用戶很少添加 http:// 字段,此代碼將為網(wǎng)址添加該字段。
- if (!preg_match(“/^(http|ftp):/”, $_POST['url'])) {
 - $_POST['url'] = ‘http://’.$_POST['url'];
 - }
 
19. PHP將網(wǎng)址字符串轉(zhuǎn)換成超級(jí)鏈接
該函數(shù)將 URL 和 E-mail 地址字符串轉(zhuǎn)換為可點(diǎn)擊的超級(jí)鏈接。
- function makeClickableLinks($text) {
 - $text = eregi_replace(‘(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)’,
 - ‘<a href=”\1″>\1</a>’, $text);
 - $text = eregi_replace(‘([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)’,
 - ‘\1<a href=”http://\2″>\2</a>’, $text);
 - $text = eregi_replace(‘([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})’,
 - ‘<a href=”mailto:\1″>\1</a>’, $text);
 - return $text;
 - }
 
20. PHP調(diào)整圖像尺寸
創(chuàng)建圖像縮略圖需要許多時(shí)間,此代碼將有助于了解縮略圖的邏輯。
- /**********************
 - *@filename – path to the image
 - *@tmpname – temporary path to thumbnail
 - *@xmax – max width
 - *@ymax – max height
 - */
 - function resize_image($filename, $tmpname, $xmax, $ymax)
 - {
 - $ext = explode(“.”, $filename);
 - $ext = $ext[count($ext)-1];
 - if($ext == “jpg” || $ext == “jpeg”)
 - $im = imagecreatefromjpeg($tmpname);
 - elseif($ext == “png”)
 - $im = imagecreatefrompng($tmpname);
 - elseif($ext == “gif”)
 - $im = imagecreatefromgif($tmpname);
 - $x = imagesx($im);
 - $y = imagesy($im);
 - if($x <= $xmax && $y <= $ymax)
 - return $im;
 - if($x >= $y) {
 - $newx = $xmax;
 - $newy = $newx * $y / $x;
 - }
 - else {
 - $newy = $ymax;
 - $newx = $x / $y * $newy;
 - }
 - $im2 = imagecreatetruecolor($newx, $newy);
 - imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
 - return $im2;
 - }
 
21. PHP檢測(cè) ajax 請(qǐng)求
大多數(shù)的 JavaScript 框架如 jquery,Mootools 等,在發(fā)出 Ajax 請(qǐng)求時(shí),都會(huì)發(fā)送額外的 HTTP_X_REQUESTED_WITH 頭部信息,頭當(dāng)他們一個(gè)ajax請(qǐng)求,因此你可以在服務(wù)器端偵測(cè)到 Ajax 請(qǐng)求。
- if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
 - strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == ‘xmlhttprequest’){
 - //If AJAX Request Then
 - }else{
 - //something else
 - }
 
到這,21個(gè)經(jīng)常用到的PHP函數(shù)代碼段,就大家介紹完了。希望對(duì)你有幫助。
【編輯推薦】















 
 
 

 
 
 
 