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

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

12. PHP创建标签云

functiongetCloud($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($dataas$tag=>$count)

{

$size=$minFontSize+ ($count–$minimumCount)

* ($maxFontSize–$minFontSize) /$spread;

$cloudTags[] = ‘

. ‘” href=”#” title=”\” .$tag.

‘\’ returned acountof ‘ .$count. ‘”>’

. htmlspecialchars(stripslashes($tag) ) . ‘

’;

}

returnjoin( “\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);

echogetCloud($arr, 12, 36);

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

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

similar_text($string1,$string2,$percent);

//$percent will have the percentage of similarity

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

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

/******************

*@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)

*/

functionshow_gravatar($email,$size,$default,$rating)

{

echo‘

‘&default=’.$default.’&size=’.$size.’&rating=’.$rating.’” width=”‘.$size.’px”

height=”‘.$size.’px” />’;

}

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

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

// Original PHP code by Chirp Internet: www.chirp.com.au

// Please acknowledge use of this code by including this header.

functionmyTruncate($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

$string=substr($string, 0,$breakpoint) .$pad;

}

}

return$string;

}

/***** Example ****/

$short_string=myTruncate($long_string, 100, ‘ ‘);

16. PHP文件 Zip 压缩

/* creates a compressed zip file */

functioncreate_zip($files=array(),$destination= ”,$overwrite= false) {

//if the zip file already exists and overwrite is false, return false

if(file_exists($destination) && !$overwrite) {returnfalse; }

//vars

$valid_files=array();

//if files were passed in…

if(is_array($files)) {

//cycle through each file

foreach($filesas$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=newZipArchive();

if($zip->open($destination,$overwrite? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {

returnfalse;

}

//add the files

foreach($valid_filesas$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

returnfile_exists($destination);

}

else

{

returnfalse;

}

}

/***** Example Usage ***/

$files=array(‘file1.jpg’, ‘file2.jpg’, ‘file3.gif’);

create_zip($files, ‘myzipfile.zip’, true);

17. PHP解压缩 Zip 文件

/**********************

*@file – path to zip file

*@destination – destination directory for unzipped files

*/

functionunzip_file($file,$destination){

// create object

$zip=newZipArchive() ;

// 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 地址预设 http 字符串

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

if(!preg_match(“/^(http|ftp):/”,$_POST['url'])) {

$_POST['url'] = ‘http://’.$_POST['url'];

}

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

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

functionmakeClickableLinks($text) {

$text=eregi_replace(‘(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)’,

‘\1’,$text);

$text=eregi_replace(‘([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)’,

‘\1\2’, $text);

$text=eregi_replace(‘([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})’,

‘\1’,$text);

return$text;

}

20. PHP调整图像尺寸

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

/**********************

*@filename – path to the image

*@tmpname – temporary path to thumbnail

*@xmax – max width

*@ymax – max height

*/

functionresize_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检测 ajax 请求

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

if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) &&

strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == ‘xmlhttprequest’){

//If AJAX Request Then

}else{

//something else

}

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

【编辑推荐】

【责任编辑:QiHappy TEL:(010)68476606】

点赞 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值