前面已经分享了25个代码片段,可以点击以下链接查看详细
1、PHP常用功能代码片段(1~5)
2、PHP常用功能代码片段(6~10)
3、PHP常用功能代码片段(11~15)
4、PHP常用功能代码片段(16~20)
5、PHP常用功能代码片段(21~25)
今天是第6篇,主要把15位身份证转换成18位、截取中英混合字符串、整个目录的拷贝功能、防止sql注入、递归法实现数组的快速排序,也就是第26到30这5个实用代码片段,希望可以帮到jquery学堂群里面的成员和广大对PHP开发的网友们提高开发效率。
26、PHP实现把15位身份证转换成18位
function getIDCard($idCard) {
// 若是15位,则转换成18位;否则直接返回ID
if (15 == strlen ( $idCard )) {
$W = array (7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1 );
$A = array ("1","0","X","9","8","7","6","5","4","3","2" );
$s = 0;
$idCard18 = substr ( $idCard, 0, 6 ) . "19" . substr ( $idCard, 6 );
$idCard18_len = strlen ( $idCard18 );
for($i = 0; $i < $idCard18_len; $i ++) {
$s = $s + substr ( $idCard18, $i, 1 ) * $W [$i];
}
$idCard18 .= $A [$s % 11];
return $idCard18;
} else {
return $idCard;
}
}
27、PHP实现截取中英混合字符串的通用方法
function cut_str($str='',$offset,$length){
$str=iconv("utf-8","gb2312",$str);
$str_len=strlen($str);
$arr=array();
for($i=0;$i<$str_len;$i++){
if(ord($str{$i})>0x80){
$arr[]=$str{$i}.$str{$i+1};
$i++;
continue;
}
$arr[]=$str{$i};
}
return array_slice($arr,$offset,$length);
}
28、PHP实现整个目录的拷贝功能
function copy_dir($src,$dst) {
$dir = opendir($src);
@mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
copy_dir($src . '/' . $file,$dst . '/' . $file);
continue;
}
else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
copy_dir('目录1','目录2');
29、PHP实现防止sql注入的通用方法
function inject_check($sql_str) {
return eregi('select|insert|and|or|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile', $sql_str);
}
function verify_id($id=null) {
if(!$id) {
exit('没有提交参数!');
} elseif(inject_check($id)) {
exit('提交的参数非法!');
} elseif(!is_numeric($id)) {
exit('提交的参数非法!');
}
$id = intval($id);
return $id;
}
function str_check( $str ) {
if(!get_magic_quotes_gpc()) {
$str = addslashes($str); // 进行过滤
}
$str = str_replace("_", "\_", $str);
$str = str_replace("%", "\%", $str);
return $str;
}
function post_check($post) {
if(!get_magic_quotes_gpc()) {
$post = addslashes($post);
}
$post = str_replace("_", "\_", $post);
$post = str_replace("%", "\%", $post);
$post = nl2br($post);
$post = htmlspecialchars($post);
return $post;
}
30、PHP用递归法实现数组的快速排序
function quicksort($seq)
{
if (count($seq) > 1) {
$k = $seq[0];
$x = array();
$y = array();
$_size = count($seq); //do not use count($seq) in loop for.
for ($i = 1; $i < $_size; $i++) {
if ($seq[$i] <= $k) {
$x[] = $seq[$i];
} else {
$y[] = $seq[$i];
}
}
$x = quicksort($x);
$y = quicksort($y);
return array_merge($x, array($k), $y);
} else {
return $seq;
}
}
如果您觉得本文的内容对您的学习有所帮助:
关键字:
php php常用功能 php代码片段 php技巧 php开发