常用的php实用小函数,看看有没有你需要的。

17-02-08 18:18 字数 875 阅读 2700 已编辑

1,获取随机字符串

//获取随机字符
function random($length = 6 , $numeric = 0) {
    PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
    if($numeric) {
        $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
    } else {
        $hash = '';
        $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
        $max = strlen($chars) - 1;
        for($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
    }
    return $hash;
}

第一个参数字符串的长度,第二个参数是否是纯数字。

2,一个简单的分页函数

/**
 * 
 * @param int $iTotal    记录总数
* @param int $iPageSize  每页数量
* @param int $iPageNo   当前页码
* @param string $sUrl   访问页url
 * @param string $sStr   url参数
* @return string
 */
function showpage($iTotal,$iPageSize,$iPageNo,$sUrl,$sStr)
{
$sString   =  "<div id="pages">";
$iPagecount    =  ceil($iTotal/$iPageSize);
$sString   .= "共 ".$iTotal." ".$sStr." 当前:第".$iPageNo."/".$iPagecount."页 ";
if($iPageNo    == 1)
   {
$sString   .= "首页 上一页 ";
   }
else
{
$sString   .= "<a href='".$sUrl."&page=1'>首页</a><a href='".$sUrl."&page=".($iPageNo-1)."'>上一页</a>";
   }
if($iPageNo    == $iPagecount    || $iPagecount    == 0)
   {
$sString   .=     "下一页 末页 ";
   }
else
{
$sString   .= "<a href='".$sUrl."&page=".($iPageNo + 1)."'>下一页</a><a href='".$sUrl."&page=".$iPagecount."'>末页</a>";
   }
$sString   .= "跳转到<select name=p onchange="javascript:window.location='".$sUrl."&page='+(this.options[this.selectedIndex].value)">";
for($i = 1 ;$i <= $iPagecount ;$i ++)
   {
if($i  == $iPageNo)
      {
$sString.="<option value=".$i." selected>第".$i."页</option>";
      }
else
{
$sString.="<option value=".$i.">第".$i."页</option>";
      }
   }
$sString   .= "</select>
   </div>";

return $sString;
}

3,无限分类--非递归

//连接数据库
$conn=mysql_connect('localhost','root','');
mysql_select_db('test');
mysql_set_charset('UTF8');
$sql="select id,concat(path,'-',id) as ppath,name from wuxianfenlei order by ppath";
$row=mysql_query($sql,$conn);
$arr=array();
$option='';
while($rows=mysql_fetch_assoc($row)){

    $peat=str_repeat("     ",substr_count($rows['ppath'],'-')-1);
    $tree=$peat.$rows['name']."<br>";
    echo $tree;
    //下拉框形式
    if($peat==''){
        $option.='<option value="'.$rows['id'].'" style="background-color:orange;">'.$peat.$rows['name'].'</option>';
    }else{
        $option.='<option value="'.$rows['id'].'">'.$peat.$rows['name'].'</option>';
    }


}
echo "<hr>";
echo '<select>'.$option.'</select>';

4,去除BOM头

$result = trim($result, "xEFxBBxBF");

如果你从文件中读取内容时遇到了一些问题,那么就试试这个函数。(我被坑了很久,两个字符串看起来一模一样,可是判断==就是返回false)

0人点赞>
关注 收藏 改进 举报
1 条评论
排序方式 时间 投票
香草大叔

很实用的php教程。[em_62]

请登录后发表评论