分享经常用到的21个PHP函数代码段(下)

开发 后端
本文介绍的是在我们实际工作中,经常用到的21个函数代码段。希望对你有帮助,一起来看。

下面介绍的是,在PHP开发中,经常用到的21个函数代码段,当我们用到的时候,就可以直接用了。

接上一篇,分享经常用到的21个PHP函数代码段(上)

12. PHP创建标签云

 

  1. function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 )  
  2. {  
  3. $minimumCount = min( array_values$data ) );  
  4. $maximumCount = max( array_values$data ) );  
  5. $spread = $maximumCount – $minimumCount;  
  6. $cloudHTML = ”;  
  7. $cloudTags = array();  
  8.  
  9. $spread == 0 && $spread = 1;  
  10.  
  11. foreach$data as $tag => $count )  
  12. {  
  13. $size = $minFontSize + ( $count – $minimumCount )  
  14. * ( $maxFontSize – $minFontSize ) / $spread;  
  15. $cloudTags[] = ‘<a style=”font-size: ‘ . floor$size ) . ‘px’  
  16. . ‘” href=”#” title=”\” . $tag .  
  17. ‘\’ returned a count of ‘ . $count . ‘”>’  
  18. . htmlspecialchars( stripslashes$tag ) ) . ‘</a>’;  
  19. }  
  20.  
  21. return join( “\n”, $cloudTags ) . “\n”;  
  22. }  
  23. /**************************  
  24. **** Sample usage ***/ 
  25. $arr = Array(‘Actionscript’ => 35, ‘Adobe’ => 22, ‘Array’ => 44, ‘Background’ => 43,  
  26. ‘Blur’ => 18, ‘Canvas’ => 33, ‘Class’ => 15, ‘Color Palette’ => 11, ‘Crop’ => 42,  
  27. ‘Delimiter’ => 13, ‘Depth’ => 34, ‘Design’ => 8, ‘Encode’ => 12, ‘Encryption’ => 30,  
  28. ‘Extract’ => 28, ‘Filters’ => 42);  
  29. echo getCloud($arr, 12, 36); 

 

13. PHP寻找两个字符串的相似性

PHP 提供了一个极少使用的 similar_text 函数,但此函数非常有用,用于比较两个字符串并返回相似程度的百分比。

 

  1. similar_text($string1$string2$percent);  
  2. //$percent will have the percentage of similarity 

 

14. PHP在应用程序中使用 Gravatar 通用头像

随着 WordPress 越来越普及,Gravatar 也随之流行。由于 Gravatar 提供了易于使用的 API,将其纳入应用程序也变得十分方便。

 

  1. /******************  
  2. *@email – Email address to show gravatar for  
  3. *@size – size of gravatar  
  4. *@default – URL of default gravatar to use  
  5. *@rating – rating of Gravatar(G, PG, R, X)  
  6. */ 
  7. function show_gravatar($email$size$default$rating)  
  8. {  
  9. echo ‘<img src=”http://www.gravatar.com/avatar.php?gravatar_id=’.md5($email).  
  10. ‘&default=’.$default.’&size=’.$size.’&rating=’.$rating.’” width=”‘.$size.’px”  
  11. height=”‘.$size.’px” />’;  

 

15. PHP在字符断点处截断文字

所谓断字 (word break),即一个单词可在转行时断开的地方。这一函数将在断字处截断字符串。

 

  1. // Original PHP code by Chirp Internet: www.chirp.com.au  
  2. // Please acknowledge use of this code by including this header.  
  3. function myTruncate($string$limit$break=”.”, $pad=”…”) {  
  4. // return with no change if string is shorter than $limit  
  5. if(strlen($string) <= $limit)  
  6. return $string;  
  7. // is $break present between $limit and the end of the string?  
  8. if(false !== ($breakpoint = strpos($string$break$limit))) {  
  9. if($breakpoint < strlen($string) – 1) {  
  10. $string = substr($string, 0, $breakpoint) . $pad;  
  11. }  
  12. }  
  13. return $string;  
  14. }  
  15. /***** Example ****/ 
  16. $short_string=myTruncate($long_string, 100, ‘ ‘); 

 

16. PHP文件 Zip 压缩

 

  1. /* creates a compressed zip file */ 
  2. function create_zip($files = array(),$destination = ”,$overwrite = false) {  
  3. //if the zip file already exists and overwrite is false, return false  
  4. if(file_exists($destination) && !$overwrite) { return false; }  
  5. //vars  
  6. $valid_files = array();  
  7. //if files were passed in…  
  8. if(is_array($files)) {  
  9. //cycle through each file  
  10. foreach($files as $file) {  
  11. //make sure the file exists  
  12. if(file_exists($file)) {  
  13. $valid_files[] = $file;  
  14. }  
  15. }  
  16. }  
  17. //if we have good files…  
  18. if(count($valid_files)) {  
  19. //create the archive  
  20. $zip = new ZipArchive();  
  21. if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {  
  22. return false;  
  23. }  
  24. //add the files  
  25. foreach($valid_files as $file) {  
  26. $zip->addFile($file,$file);  
  27. }  
  28. //debug  
  29. //echo ‘The zip archive contains ‘,$zip->numFiles,’ files with a status of ‘,$zip->status;  
  30. //close the zip — done!  
  31. $zip->close();  
  32. //check to make sure the file exists  
  33. return file_exists($destination);  
  34. }  
  35. else 
  36. {  
  37. return false;  
  38. }  
  39. }  
  40. /***** Example Usage ***/ 
  41. $files=array(‘file1.jpg’, ‘file2.jpg’, ‘file3.gif’);  
  42. create_zip($files, ‘myzipfile.zip’, true); 

 

#p#

17. PHP解压缩 Zip 文件

 

  1. /**********************  
  2. *@file – path to zip file  
  3. *@destination – destination directory for unzipped files  
  4. */ 
  5. function unzip_file($file$destination){  
  6. // create object  
  7. $zip = new ZipArchive() ;  
  8. // open archive  
  9. if ($zip->open($file) !== TRUE) {  
  10. die (’Could not open archive’);  
  11. }  
  12. // extract contents to destination directory  
  13. $zip->extractTo($destination);  
  14. // close archive  
  15. $zip->close();  
  16. echo ‘Archive extracted to directory’;  

 

18. PHP为 URL 地址预设 http 字符串

有时需要接受一些表单中的网址输入,但用户很少添加 http:// 字段,此代码将为网址添加该字段。

 

  1. if (!preg_match(“/^(http|ftp):/”, $_POST['url'])) {  
  2. $_POST['url'] = ‘http://’.$_POST['url'];  

 

19. PHP将网址字符串转换成超级链接

该函数将 URL 和 E-mail 地址字符串转换为可点击的超级链接。

 

  1. function makeClickableLinks($text) {  
  2. $text = eregi_replace(‘(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)’,  
  3. ‘<a href=”\1″>\1</a>’, $text);  
  4. $text = eregi_replace(‘([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)’,  
  5. ‘\1<a href=”http://\2″>\2</a>’, $text);  
  6. $text = eregi_replace(‘([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})’,  
  7. ‘<a href=”mailto:\1″>\1</a>’, $text);  
  8. return $text;  

 

20. PHP调整图像尺寸

创建图像缩略图需要许多时间,此代码将有助于了解缩略图的逻辑。

 

  1. /**********************  
  2. *@filename – path to the image  
  3. *@tmpname – temporary path to thumbnail  
  4. *@xmax – max width  
  5. *@ymax – max height  
  6. */ 
  7. function resize_image($filename$tmpname$xmax$ymax)  
  8. {  
  9. $ext = explode(“.”, $filename);  
  10. $ext = $ext[count($ext)-1];  
  11.  
  12. if($ext == “jpg” || $ext == “jpeg”)  
  13. $im = imagecreatefromjpeg($tmpname);  
  14. elseif($ext == “png”)  
  15. $im = imagecreatefrompng($tmpname);  
  16. elseif($ext == “gif”)  
  17. $im = imagecreatefromgif($tmpname);  
  18.  
  19. $x = imagesx($im);  
  20. $y = imagesy($im);  
  21.  
  22. if($x <= $xmax && $y <= $ymax)  
  23. return $im;  
  24.  
  25. if($x >= $y) {  
  26. $newx = $xmax;  
  27. $newy = $newx * $y / $x;  
  28. }  
  29. else {  
  30. $newy = $ymax;  
  31. $newx = $x / $y * $newy;  
  32. }  
  33.  
  34. $im2 = imagecreatetruecolor($newx$newy);  
  35. imagecopyresized($im2$im, 0, 0, 0, 0, floor($newx), floor($newy), $x$y);  
  36. return $im2;  

 

21. PHP检测 ajax 请求

大多数的 JavaScript 框架如 jquery,Mootools 等,在发出 Ajax 请求时,都会发送额外的 HTTP_X_REQUESTED_WITH 头部信息,头当他们一个ajax请求,因此你可以在服务器端侦测到 Ajax 请求。

 

  1. if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
  2. strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == ‘xmlhttprequest’){  
  3. //If AJAX Request Then  
  4. }else{  
  5. //something else  
  6. }  

 

到这,21个经常用到的PHP函数代码段,就大家介绍完了。希望对你有帮助。

【编辑推荐】

  1. php基础 关于继承的使用方法
  2. 介绍生成PHP网站页面静态化的方法
  3. PHP新手 详细介绍PHP代码规范
  4. PHP中IIS7实现基本身份验证的方法
  5. 分享PHP网站建设的流程与步骤
责任编辑:于铁 来源: 大家论坛
相关推荐

2011-07-07 17:24:28

PHP

2012-05-29 13:34:39

2015-10-29 10:30:41

C#程序员实用代码

2015-08-19 09:15:11

C#程序员实用代码

2009-12-02 20:29:30

PHP常用函数

2009-05-18 16:59:42

代码PHP编码

2011-07-10 00:02:39

PHP

2009-12-03 16:54:36

PHP获取中国IP段

2011-07-14 10:07:19

PHP

2011-07-11 10:24:09

PHP

2019-12-25 15:40:28

内存Java虚拟机

2011-02-24 09:41:25

PHP代码

2010-10-08 16:32:59

MySQL语句

2011-01-10 10:57:33

WebPHPJavaScript

2021-08-19 08:31:46

云计算

2009-12-08 19:24:09

PHP函数索引

2020-10-14 18:53:14

Python编程语言

2009-12-08 14:00:11

PHP函数microt

2009-12-01 10:50:45

PHP函数requir

2012-03-28 09:49:55

WEB特效
点赞
收藏

51CTO技术栈公众号