PHP 几种常用的算法整理
一、冒泡排序
<?php $arr=array(1,5,9,7,2,8,4,3,6); //控制冒泡的轮次 for($i=1;$i<count($arr);$i++) { //控制需要比较的次数,每轮冒出一个数 for($k=0;$k<count($arr)-$i;$k++){ if($arr[$k]>$arr[$k+1]){ $tmp=$arr[$k+1]; $arr[$k+1]=$arr[$k]; $arr[$k]=$tmp; } } } print_r($arr);
二、利用PHP内置函数计算字符串长度
<?php $str = "Hello,world"; $count = 0; while (1){ if (@$str[$count] != NULL){ $count++; continue; }else{ break; } } echo $count;
三、反向输出字符串
<?php $str = "Hello,world"; if ($str == '') echo 0; $bstr = ""; for ($i=(strlen($str)- 1); $i>=0; $i --){ $bstr .= $str[$i ]; } echo $bstr;
四、加密,解密
<?php $str = "hello,world"; $key = "www.cnblogs.com"; $str = $str.$key; $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+"; $rand = rand(0,64); $ch = $chars[$rand]; $mdKey = md5($key.$ch); $mdKey = substr($mdKey,$rand%8, $rand%8+7); $str = base64_encode($str); $tmp = ''; $i=0;$j=0;$k = 0; for ($i=0; $i<strlen($str); $i++) { $k = $k == strlen($mdKey) ? 0 : $k; $j = ($rand+strpos($chars,$str[$i])+ord($mdKey[$k++]))%64; $tmp .= $chars[$j]; } echo urlencode(base64_encode($ch.$tmp)); <?php $str = "YWFSU3FtUzYycDJJdlpSZDFuRGM1VjBFdVpRSm5udjN1bjAtTA%3D%3D"; $key = "www.cnblogs.com"; $str = base64_decode(urldecode($str)); $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+"; $ch = $str[0]; $rand = strpos($chars,$ch); $mdKey = md5($key.$ch); $mdKey = substr($mdKey,$rand%8, $rand%8+7); $str = substr($str,1); $tmp = ''; $i=0;$j=0; $k = 0; for ($i=0; $i<strlen($str); $i++) { $k = $k == strlen($mdKey) ? 0 : $k; $j = strpos($chars,$str[$i])-$rand - ord($mdKey[$k++]); while ($j<0) $j+=64; $tmp .= $chars[$j]; } echo trim(base64_decode($tmp),$key);
.....