php中网址、email、手机号码正则表达代码

 更新时间:2016年11月25日 15:48  点击:2107
本文章来详细的介绍一在我们php开发中常用的几种正则表达式,如有网址、email、手机号码正则表达代码

1. 判断Email:

域名由各国文字的特定字符集、英文字母、数字及“-”(即连字符或减号)任意组合而成, 但开头及结尾均不能含有“-”,“-”不能连续出现 。 域名中字母不分大小写。域名最长可达60个字节(包括后缀.com、.net、.org等)。
/^[a-z]([a-z0-9]*[-_]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?$/i;
/内容/i 构成一个不区分大小写的正则表达式;

基本规则如下

 代码如下 复制代码
preg_match('/^[a-z0-9_-]+(.[_a-z0-9-]+)*@([_a-z0-9-]+.)+([a-z]{2}
|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)$/',$email)

例1

 代码如下 复制代码

<?php
function is_email($email){
return strlen($email) > 6 && preg_match(“/^[w-.]+@[w-]+(.w+)+$/“, $email);
}
?>

例2

 代码如下 复制代码

<html>
     <body>
         <?php
             $email_pattern = '/w{6,16}@w{1,}.w{2,3}/i';   
             $email_valid = 'test_123@126.net';
             $email_invalid = 'test@test%@111@com';
             $matches = array();
            
             preg_match($email_pattern, $email_valid, $matches[]);
             preg_match($email_pattern, $email_invalid, $matches[]);
            
             var_dump($matches);
         ?>
     </body>
 </html>

结果

array(2) { [0]=> array(1) { [0]=> string(16) "test_123@126.net" } [1]=> array(0) { } }

2. 判断Url:

例1

 代码如下 复制代码

function is_url($str){
return preg_match(“/^http://[A-Za-z0-9]+.[A-Za-z0-9]+[/=?%-&_~`@[]’:+!]*([^<>"])*$/“, $str);
}


例2

php判断url地址并自动转换为超链接,在一段字符串中用正则表达式匹配出url,在将url转换为超链接,点击可访问地址

 代码如下 复制代码

<?php
function autolink($foo)
{
$foo = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_/+.~#?&//=]+)', '<a href="/1" mce_href="/1" target=_blank rel=nofollow>/1</a>', $foo);
if( strpos($foo, "http") === FALSE ){
$foo = eregi_replace('(www.[-a-zA-Z0-9@:%_/+.~#?&//=]+)', '<a href="http:///1" mce_href="http:///1" target=_blank rel=nofollow >/1</a>', $foo);
}else{
$foo = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_/+.~#?&//=]+)', '/1<a href="http:///2" mce_href="http:///2" target=_blank rel=nofollow >/2</a>', $foo);
}
return $foo;
}

?>


3. 判断手机号码:

例1

 代码如下 复制代码

function is_mobile($str){
return preg_match(“/^(((d{3}))|(d{3}-))?13d{9}$/“, $str);
}

例2

if(preg_match("/^13[0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/",$mobilephone)){   
    //验证通过   
       
}else{   
    //手机号码格式不对   
       
}

在很多朋友写无限级分类数据时都直接使用递归来操作,下面我来介绍一下关于PHP无限分级代码优化方法,有需要的朋友可参考参考。
 代码如下 复制代码

/**
 * 创建父节点树形数组
 * 参数
 * $ar 数组,邻接列表方式组织的数据
 * $id 数组中作为主键的下标或关联键名
 * $pid 数组中作为父键的下标或关联键名
 * 返回 多维数组
 **/
function find_parent($ar, $id='id', $pid='pid') {
  foreach($ar as $v) $t[$v[$id]] = $v;
  foreach ($t as $k => $item){
    if( $item[$pid] ){
      if( ! isset($t[$item[$pid]]['parent'][$item[$pid]]) )
         $t[$item[$id]]['parent'][$item[$pid]] =& $t[$item[$pid]];

          $t[$k]['reference'] = true;
    }
  }
  return $t;
}


/**
 * 创建子节点树形数组
 * 参数
 * $ar 数组,邻接列表方式组织的数据
 * $id 数组中作为主键的下标或关联键名
 * $pid 数组中作为父键的下标或关联键名
 * 返回 多维数组
 **/
function find_child($ar, $id='id', $pid='pid') {
  foreach($ar as $v) $t[$v[$id]] = $v;
  foreach ($t as $k => $item){
    if( $item[$pid] ) {
      $t[$item[$pid]]['child'][$item[$id]] =& $t[$k];

      $t[$k]['reference'] = true;
    }
  }
  return $t;
}

 

示例:


$data = array(
    array('ID'=>1, 'PARENT'=>0, 'NAME'=>'祖父'),
    array('ID'=>2, 'PARENT'=>1, 'NAME'=>'父亲'),
    array('ID'=>3, 'PARENT'=>1, 'NAME'=>'叔伯'),
    array('ID'=>4, 'PARENT'=>2, 'NAME'=>'自己'),
    array('ID'=>5, 'PARENT'=>4, 'NAME'=>'儿子')
);
$p = find_parent($data, 'ID', 'PARENT');
$c = find_child($data, 'ID', 'PARENT');

上面两种方法是将所有节点按id平摊到一个数组中,然后找到他们的 parent 或 children ,通过引用将 平摊的元素挂接到 parent 、children 下,

但被引用的元素依然存在于平摊的数组中,因此,在实际应用时,最好标记那些被引用的元素,以避免以他们为根开始遍历,导致重复。


        foreach ($p as $key => $item) {
            if($item['reference']) continue;
            print_r($item);
        }

        foreach ($c as $key => $item) {
            if($item['reference']) continue;
            print_r($item);
        }

 

递归法,PHP 数组元素被删除后,数组游标会归零,因此在遍历过程中一些已经找到 “归宿” 的元素也不得不留在数组中,无法缩减后继元素的搜索范围:


$mylist = array(array( 'parent_id'=>0,'id'=>1),
                    array( 'parent_id'=>0,'id'=>2),
                    array( 'parent_id'=>0,'id'=>3),   
                    array( 'parent_id'=>2,'id'=>4),
                    array( 'parent_id'=>2,'id'=>5),
                    array( 'parent_id'=>3,'id'=>6),
                    array( 'parent_id'=>3,'id'=>7),   
                    array( 'parent_id'=>4,'id'=>8),
                    array( 'parent_id'=>5,'id'=>9),
                    array( 'parent_id'=>5,'id'=>10)
                );

 

    function _findChildren($list, $p_id){    //数据层级化,
          $r = array();
          foreach($list as $id=>$item){
            if($item['parent_id'] == $p_id) {
                   $length = count($r);
                  $r[$length] = $item;
                  if($t = $this->_findChildren($list, $item['id']) ){
                      $r[$length]['children'] = $t;
                  }               
            }
          }
          return $r;
    } 
 

print_r(_findChildren($mylist, 0));

例如搜索“ok”就会匹配ok里面的数组 “你好,good,很好\"打印出来如果搜索“好”没有匹配到第一数组,就会模糊搜索所有含有“好”的的关键词,例如“你好 很好 爱好”

如下面例子:

 代码如下 复制代码

$foo[1]['a']['xx'] = 'bar 1';
$foo[1]['b']['xx'] = 'bar 2';
$foo[2]['a']['bb'] = 'bar 3';
$foo[2]['a']['yy'] = 'bar 4';
$foo[3]['c']['dd'] = 'bar 3';
$foo[3]['f']['gg'] = 'bar 3';
$foo['info'][1] = 'bar 5';

如果要查找 bar 3 怎么进行查找呢。有三个结果,而这三个结果都要,看下面的函数:
-------------------------------------------------------------------------------------------------------------------------------

 代码如下 复制代码
function array_search_re($needle, $haystack, $a=0, $nodes_temp=array()){
global $nodes_found;
$a++;
foreach ($haystack as $key1=>$value1) {
    $nodes_temp[$a] = $key1;
    if (is_array($value1)){  
      array_search_re($needle, $value1, $a, $nodes_temp);
    }
    else if ($value1 === $needle){
      $nodes_found[] = $nodes_temp;
    }
}
return $nodes_found;
}

---------------------------------------------------------------------------------------------------------------------------------
这个函数就可以把上面要查找到的内容全部返回出键名来

 代码如下 复制代码

$result = array_search_re('bar 3', $foo);

print_r($result);

输出结果为如下:
Array ( [0] => Array ( [1] => 2 [2] => a [3] => bb )
          [1] => Array ( [1] => 3 [2] => c [3] => dd )
          [2] => Array ( [1] => 3 [2] => f [3] => gg )
        )

1 php搜索多维数组的键名

 代码如下 复制代码

function array_search_key($needle, $haystack){
global $nodes_found;

foreach ($haystack as $key1=>$value1) {
 
 if ($key1=== $needle){
 
  $nodes_found[] = $value1;
      
   }
    if (is_array($value1)){  
      array_search_key($needle, $value1);
    }
  
  
}

return $nodes_found;
}
$result = array_search_key('a', $foo);

print_r($result);

输出结果为如下:
 

 代码如下 复制代码

Array
(
    [0] => Array
        (
            [xx] => bar 1
        )

    [1] => Array
        (
            [bb] => bar 3
        )

    [2] => Array
        (
            [yy] => bar 4
        )

)

类似全文匹配!用二个循环 第一个循环keys  第二个模糊匹配 用函数strstr() 来解决

PHP分页器制作,自动生成分面页码,JS调用函数,分页的原理大致如下,分页程序有两个非常重要的参数:每页显示几条记录($pagesize)和当前是第几页($page)。

有了这两个参数就可以很方便的写出分页程序,我们以MySql数据库作为数据源,在mysql里如果要想取出表内某段特定内容可以使用的 T-SQL语句:select * from table limit offset,rows来实现。这里的offset是记录偏移量,它的计算方法是offset=$pagesize*($page-1),rows是要显示的记录条数,这里就是$page。也就是说select * from table limit 10,10这条语句的意思是取出表里从第11条记录开始的20条记录。

 代码如下 复制代码

<?php
class PageView{
    /**页码**/
    public $pageNo = 1;
    /**页大小**/
    public $pageSize = 20;
    /**共多少页**/
    public $pageCount = 0;
    /**总记录数**/
    public $totalNum = 0;
    /**偏移量,当前页起始行**/
    public $offSet = 0;
    /**每页数据**/
    public $pageData = array();
   
    /**是否有上一页**/
    public $hasPrePage = true;
    /**是否有下一页**/
    public $hasNextPage = true;
   
    public $pageNoList = array();
   
    public $jsFunction ='jsFunction';
    /**
     *
     * @param unknown_type $count 总行数
     * @param unknown_type $size 分页大小
     * @param unknown_type $string
     */
    public function __construct($count=0, $size=20,$pageNo=1,$pageData =array(),$jsFunction='jsFunction'){

        $this->totalNum = $count;//总记录数
        $this->pageSize = $size;//每页大小
        $this->pageNo = $pageNo;
        //计算总页数
        $this->pageCount = ceil($this->totalNum/$this->pageSize);
        $this->pageCount = ($this->pageCount<=0)?1:$this->pageCount;
        //检查pageNo
        $this->pageNo = $this->pageNo == 0 ? 1 : $this->pageNo;
        $this->pageNo = $this->pageNo > $this->pageCount? $this->pageCount : $this->pageNo;
       
        //计算偏移
        $this->offset = ( $this->pageNo - 1 ) * $this->pageSize;
        //计算是否有上一页下一页
        $this->hasPrePage = $this->pageNo == 1 ?false:true;

        $this->hasNextPage = $this->pageNo >= $this->pageCount ?false:true;
       
        $this->pageData = $pageData;
        $this->jsFunction = $jsFunction;
       
    }
    /**
     * 分页算法
     * @return
     */
    private function generatePageList(){
        $pageList = array();
        if($this->pageCount <= 9){
            for($i=0;$i<$this->pageCount;$i++){
                array_push($pageList,$i+1);
            }
        }else{
            if($this->pageNo <= 4){
                for($i=0;$i<5;$i++){
                    array_push($pageList,$i+1);
                }
                array_push($pageList,-1);
                array_push($pageList,$this->pageCount);

            }else if($this->pageNo > $this->pageCount - 4){
                array_push($pageList,1);
               
                array_push($pageList,-1);
                for($i=5;$i>0;$i--){
                    array_push($pageList,$this->pageCount - $i+1);
                }
            }else if($this->pageNo > 4 && $this->pageNo <= $this->pageCount - 4){
                array_push($pageList,1);
                array_push($pageList,-1);
               
                array_push($pageList,$this->pageNo -2);
                array_push($pageList,$this->pageNo -1);
                array_push($pageList,$this->pageNo);
                array_push($pageList,$this->pageNo + 1);
                array_push($pageList,$this->pageNo + 2);
               
                array_push($pageList,-1);
                array_push($pageList,$this->pageCount);
               
            }
        }
        return $pageList;
    }

    /***
     * 创建分页控件
    * @param
    * @return String
    */
    public function echoPageAsDiv(){
        $pageList = $this->generatePageList();
       
        $pageString ="<div class='pagination'><div class='page-bottom'>";
   
        if(!empty($pageList)){
            if($this->pageCount >1){
                if($this->hasPrePage){
                    $pageString = $pageString ."<a class='page-next' href="javascript:" .$this->jsFunction . "(" . ($this->pageNo-1) . ")">上一页</a>";
                }
                foreach ($pageList as $k=>$p){
                    if($this->pageNo == $p){
                        $pageString = $pageString ."<span class='page-cur'>" . $this->pageNo . "</span>";
                        continue;
                    }
                    if($p == -1){
                        $pageString = $pageString ."<span class='page-break'>...</span>";
                        continue;
                    }
                    $pageString = $pageString ."<a href="javascript:" .$this->jsFunction . "(" . $p . ")">" . $p . "</a>";
                }
               
                if($this->hasNextPage){
                    $pageString = $pageString ."<a class='page-next' href="javascript:" .$this->jsFunction . "(" . ($this->pageNo+1) . ")">下一页</a>";
                }
               
            }
        }
        $pageString = $pageString .("</div></div>");
        return $pageString;
    }
}

?>

css

 代码如下 复制代码

<style type="text/css">
<!--
.pagination {font-family: Tahoma;overflow: hidden; padding-top: 12px; text-align: center;}
.pagination-tab { margin-bottom: 20px;}
.pagination a, .pagination .page-cur, .pagination .page-prev_g, .pagination .page-prev, .pagination .page-next, .pagination .page-next_g, .pagination .page-break, .pagination .page-skip {
    display: inline-block;font-family: Tahoma,SimSun,Arial; height: 22px;line-height:22px; margin: 0; min-width: 16px;padding: 0 5px; text-align: center; vertical-align: top; white-space: nowrap;}
.pagination a, .pagination .page-prev_g, .pagination .page-prev, .pagination .page-next, .pagination .page-next_g, .pagination .page-cur, .pagination .page-break {
    border: 1px solid #ed3d83; color:#e9357d; font-weight:bold;}
.pagination a:hover { border: 1px solid #ed3d83;text-decoration: none; background-color:#f95f9d; color:#fff;}
.pagination .page-prev_g, .pagination .page-prev, .pagination .page-next, .pagination .page-next_g { width: 36px; background-image: url(../static/img/page.gif);}
.pagination .page-prev { background-position: -0px -38px; padding-left: 16px;}
.pagination .page-prev_g { background-position:0px -59px; padding-left: 16px; color:#cbcbcb; font-weight:normal;}
.pagination .page-next { background-position: 0px 0px; padding-right: 16px; font-weight:normal;}
.pagination .page-next_g { background-position: -0px -19px; padding-right: 16px; color:#cbcbcb;}
.pagination .page-cur {background-color: #f95f9d; border: 1px solid #ed3d83;color: #fff;font-weight: bold;}
.pagination .page-break {border: medium none; background:none transparent; color:#333;}

-->
</style>

使用方法

 代码如下 复制代码

$pageNo = $_GET['pageNo'];
        if(empty($pageNo)){
            $pageNo = 1;
        }
        //分页数据
        $pageData = News::getNewsPage($pageNo,$pageSize);
       //取得总行数
        $count = News::getNewsCount();
        //创建分页器
        $p = new PageView($count['0']['TOTAL'],$pageSize,$pageNo,$pageData);
     //生成页码
$pageViewString = $p->echoPageAsDiv();


 

下面再介绍一个分页类

 代码如下 复制代码

<?php  
class SubPages{  
     
   private  $each_disNums;//每页显示的条目数  
  private  $nums;//总条目数  
  private  $current_page;//当前被选中的页  
  private  $sub_pages;//每次显示的页数  
  private  $pageNums;//总页数  
  private  $page_array = array();//用来构造分页的数组  
  private  $subPage_link;//每个分页的链接  
  private  $subPage_type;//显示分页的类型  
   /* 
   __construct是SubPages的构造函数,用来在创建类的时候自动运行. 
   @$each_disNums   每页显示的条目数 
   @nums     总条目数 
   @current_num     当前被选中的页 
   @sub_pages       每次显示的页数 
   @subPage_link    每个分页的链接 
   @subPage_type    显示分页的类型 
    
   当@subPage_type=1的时候为普通分页模式 
         example:   共4523条记录,每页显示10条,当前第1/453页 [首页] [上页] [下页] [尾页] 
         当@subPage_type=2的时候为经典分页样式 
         example:   当前第1/453页 [首页] [上页] 1 2 3 4 5 6 7 8 9 10 [下页] [尾页] 
   */ 
  function __construct($each_disNums,$nums,$current_page,$sub_pages,$subPage_link,$subPage_type){  
   $this->each_disNums=intval($each_disNums);  
   $this->nums=intval($nums);  
    if(!$current_page){  
    $this->current_page=1;  
    }else{  
    $this->current_page=intval($current_page);  
    }  
   $this->sub_pages=intval($sub_pages);  
   $this->pageNums=ceil($nums/$each_disNums);  
   $this->subPage_link=$subPage_link;   
   $this->show_SubPages($subPage_type);   
   //echo $this->pageNums."--".$this->sub_pages;  
  }  
     
     
  /* 
    __destruct析构函数,当类不在使用的时候调用,该函数用来释放资源。 
   */ 
  function __destruct(){  
    unset($each_disNums);  
    unset($nums);  
    unset($current_page);  
    unset($sub_pages);  
    unset($pageNums);  
    unset($page_array);  
    unset($subPage_link);  
    unset($subPage_type);  
   }  
     
  /* 
    show_SubPages函数用在构造函数里面。而且用来判断显示什么样子的分页   
   */ 
  function show_SubPages($subPage_type){  
    if($subPage_type == 1){  
    $this->subPageCss1();  
    }elseif ($subPage_type == 2){  
    $this->subPageCss2();  
    }  
   }  
     
     
  /* 
    用来给建立分页的数组初始化的函数。 
   */ 
  function initArray(){  
    for($i=0;$i<$this->sub_pages;$i++){  
    $this->page_array[$i]=$i;  
    }  
    return $this->page_array;  
   }  
     
     
  /* 
    construct_num_Page该函数使用来构造显示的条目 
    即使:[1][2][3][4][5][6][7][8][9][10] 
   */ 
  function construct_num_Page(){  
    if($this->pageNums < $this->sub_pages){  
    $current_array=array();  
     for($i=0;$i<$this->pageNums;$i++){   
     $current_array[$i]=$i+1;  
     }  
    }else{  
    $current_array=$this->initArray();  
     if($this->current_page <= 3){  
      for($i=0;$i<count($current_array);$i++){  
      $current_array[$i]=$i+1;  
      }  
     }elseif ($this->current_page <= $this->pageNums && $this->current_page > $this->pageNums - $this->sub_pages + 1 ){  
      for($i=0;$i<count($current_array);$i++){  
      $current_array[$i]=($this->pageNums)-($this->sub_pages)+1+$i;  
      }  
     }else{  
      for($i=0;$i<count($current_array);$i++){  
      $current_array[$i]=$this->current_page-2+$i;  
      }  
     }  
    }  
      
    return $current_array;  
   }  
     
  /* 
   构造普通模式的分页 
   共4523条记录,每页显示10条,当前第1/453页 [首页] [上页] [下页] [尾页] 
   */ 
  function subPageCss1(){  
   $subPageCss1Str="";  
   $subPageCss1Str.="共".$this->nums."条记录,";  
   $subPageCss1Str.="每页显示".$this->each_disNums."条,";  
   $subPageCss1Str.="当前第".$this->current_page."/".$this->pageNums."页 ";  
    if($this->current_page > 1){  
    $firstPageUrl=$this->subPage_link."1";  
    $prewPageUrl=$this->subPage_link.($this->current_page-1);  
    $subPageCss1Str.="[<a href='$firstPageUrl'>首页</a>] ";  
    $subPageCss1Str.="[<a href='$prewPageUrl'>上一页</a>] ";  
    }else {  
    $subPageCss1Str.="[首页] ";  
    $subPageCss1Str.="[上一页] ";  
    }  
      
    if($this->current_page < $this->pageNums){  
    $lastPageUrl=$this->subPage_link.$this->pageNums;  
    $nextPageUrl=$this->subPage_link.($this->current_page+1);  
    $subPageCss1Str.=" [<a href='$nextPageUrl'>下一页</a>] ";  
    $subPageCss1Str.="[<a href='$lastPageUrl'>尾页</a>] ";  
    }else {  
    $subPageCss1Str.="[下一页] ";  
    $subPageCss1Str.="[尾页] ";  
    }  
      
    echo $subPageCss1Str;  
      
   }  
     
     
  /* 
   构造经典模式的分页 
   当前第1/453页 [首页] [上页] 1 2 3 4 5 6 7 8 9 10 [下页] [尾页] 
   */ 
  function subPageCss2(){  
   $subPageCss2Str="";  
   $subPageCss2Str.="当前第".$this->current_page."/".$this->pageNums."页 ";  
      
      
    if($this->current_page > 1){  
    $firstPageUrl=$this->subPage_link."1";  
    $prewPageUrl=$this->subPage_link.($this->current_page-1);  
    $subPageCss2Str.="[<a href='$firstPageUrl'>首页</a>] ";  
    $subPageCss2Str.="[<a href='$prewPageUrl'>上一页</a>] ";  
    }else {  
    $subPageCss2Str.="[首页] ";  
    $subPageCss2Str.="[上一页] ";  
    }  
      
   $a=$this->construct_num_Page();  
    for($i=0;$i<count($a);$i++){  
    $s=$a[$i];  
     if($s == $this->current_page ){  
     $subPageCss2Str.="[<span style='color:red;font-weight:bold;'>".$s."</span>]";  
     }else{  
     $url=$this->subPage_link.$s;  
     $subPageCss2Str.="[<a href='$url'>".$s."</a>]";  
     }  
    }  
      
    if($this->current_page < $this->pageNums){  
    $lastPageUrl=$this->subPage_link.$this->pageNums;  
    $nextPageUrl=$this->subPage_link.($this->current_page+1);  
    $subPageCss2Str.=" [<a href='$nextPageUrl'>下一页</a>] ";  
    $subPageCss2Str.="[<a href='$lastPageUrl'>尾页</a>] ";  
    }else {  
    $subPageCss2Str.="[下一页] ";  
    $subPageCss2Str.="[尾页] ";  
    }  
    echo $subPageCss2Str;  
   }  
}  
?>

调用方法

 代码如下 复制代码

<?php  
require_once("SubPages.php");  
//每页显示的条数  
  $page_size=20;  
//总条目数  
  $nums=1024;  
//每次显示的页数  
  $sub_pages=10;  
//得到当前是第几页  
  $pageCurrent=$_GET["p"];  
  //if(!$pageCurrent) $pageCurrent=1;  
     
  $subPages=new SubPages($page_size,$nums,$pageCurrent,$sub_pages,"test.php?p=",2);  
?>

本文章是一个自己的对CI框架的学习笔记,用一个完整的搜索,查找并且实现分页的程序给大家参考参考。

举个按关键词搜索结果分页的例子,
1.视图HTML

 代码如下 复制代码

<div id="body">
<form action="/index.php/search/index/" method="get">
<p>请输入书名、作者、出版社中的一个或多个来查询。</p>
<p><input type="text" name="s" value="" size="64" /> <input type="submit" value="搜索" /></p>
</form>
</div>


即表单提交到名叫search的controller和名叫index的方法, 其中包含了一些动态参数,不是纯列表,故相对比较复杂,后面会提到。

 代码如下 复制代码

public function index() {
$keyword = $this->input->get ( 's' );
$offset = $this->input->get ( 'offset' );

if (empty ( $offset )) {
$offset = 0;
}

if (! empty ( $keyword )) {
$this->load->model ( 'book_model' );
$this->load->library ( 'pagination' );

$per_page = 10;
$config ['num_links'] = 5;
$config ['base_url'] = '/index.php/' . $this->router->class . '/' . $this->router->method . '/?s=' . $keyword;
$config ['per_page'] = $per_page;
$config ['total_rows'] = $this->Book_Model->find_by_name ( $keyword, NULL, NULL, true );
$config ['page_query_string'] = false;
$config ['query_string_segment'] = 'offset'; //重新定义记录起始位置的参数名,默认为per_page

$this->pagination->initialize ( $config );
$data ['books'] = $this->Book_Model->find_by_name ( $keyword, $per_page, $offset );
$this->load->view ( 'search', $data );
} else {
$this->load->view ( 'search' );
}
}

因为config.php中默认的enable_query_strings是false, 起始位置始终在最后,这样出来的结果类似/index.php/search/index/?s=中国/10,页码取不到,需要将此配置改为false;

3.模型

 

 代码如下 复制代码
public function find_by_name($name, $per_page=0, $offset = 0, $is_total = false) {
if ($is_total) {//总数
$query = $this->db->query ( "select count(id) as cnt from {$this->_book} where book_name like '%{$name}%'" );
if ($query->num_rows () > 0) {
$row = $query->row ();
$ret = $row->cnt;
}
}else{//列表
$query = $this->db->query ("select * from {$this->_book} where book_name like '%{$name}%' limit {$offset}, {$per_page}");
$ret = $query->result ();
}
return $ret;
}
[!--infotagslink--]

相关文章

  • 怎么查询自己的联通手机号码是否已经实名认证(实名制)?

    怎么查询自己的联通手机号码是否已经实名认证?现在手机一批一批的开始实名制了,自己的手机号买的时候没有实名认证,怎么才能知道自己的手机是否被知名认证了呢?认证以后就不能充话费打电话了,下面我们们一起来看看两种查看方法...2016-07-04
  • 一个关于JS正则匹配的踩坑记录

    这篇文章主要给大家介绍了一个关于JS正则匹配的踩坑记录,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-04-13
  • 微信小程序开发之获取用户手机号码(php接口解密)

    这篇文章主要介绍了微信小程序开发之获取用户手机号码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-05-18
  • js正则学习小记之匹配字符串字面量

    关于匹配字符串问题,有很多种类型,今天讨论 js 代码里的字符串匹配,因为我想学完之后写个语法高亮练手,所以用js代码当作例子...2021-05-07
  • js 正则学习小记之匹配字符串字面量优化篇

    昨天在《js 正则学习小记之匹配字符串字面量》谈到 /"(?:\\.|[^"])*"/ 是个不错的表达式,因为可以满足我们的要求,所以这个表达式可用,但不一定是最好的...2021-05-07
  • C#使用正则表达式过滤html标签

    最近在开发一个项目,其中有需求要求我们把一段html转换为一般文本返回,使用正则表达式是明智的选择,下面小编给介绍下C#使用正则表达式过滤html标签,需要的朋友参考下...2020-06-25
  • JS基于正则截取替换特定字符之间字符串操作示例

    这篇文章主要介绍了JS基于正则截取替换特定字符之间字符串操作方法,结合具体实例形式分析了JS基于正则实现针对特殊字符、数字等字符串类型的截取操作相关技巧,需要的朋友可以参考下...2017-02-08
  • javascript 手机号码正则表达式验证函数 <font color=red>原创</font>

    随着手机号码段的不断增加,以前网上的手机号码验证函数都不能那么完美的支持了,这里脚本之家编辑特为大家准备的一个简单的正则与手机验证的函数分析。...2021-05-07
  • 浅谈JS正则RegExp对象

    这篇文章主要介绍JS正则RegExp对象,正则表达式是描述字符模式的对象,用于对字符串模式匹配及检索替换,是对字符串执行模式匹配的强大工具。下面就来看具体详情,需要的朋友可以参考一下...2021-10-21
  • OpenResty中正则模式匹配的2种方法详解

    在 OpenResty 中,同时存在两套正则表达式规范:Lua 语言的规范和 Nginx 的规范,下面这篇文章主要给大家介绍了关于OpenResty中正则模式匹配的2种方法,文中通过示例代码介绍的非常详细,需要的朋友可以参考下。...2020-06-30
  • 浅谈C#手机号换成111XXXX1111 这种显示的解决思路

    下面小编就为大家带来一篇浅谈C#手机号换成111XXXX1111 这种显示的解决思路。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • 浅谈js正则之test方法bug篇

    其实我很少用这个,所以之前一直没注意这个问题,自从落叶那厮写了个变态的测试我才去看了下这东西...2021-05-07
  • JS利用正则配合replace替换指定字符

    替换指定字符的方法有很多,在本文为大家详细介绍下,JS利用正则配合replace是如何做到的,喜欢的朋友可以参考下...2021-05-07
  • Spring-AOP 静态正则表达式方法如何匹配切面

    这篇文章主要介绍了Spring-AOP 静态正则表达式方法如何匹配切面的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-07-19
  • php正则中文表达式

    php教程正则中文表达式 $str = "abc一二三cde"; echo preg_replace('/[^x4e00-x9fa5]/i'," ",$str); $str = "php编程"; if (preg_match("/^[x4e00-x9fa5]+$/u",$s...2016-11-25
  • php正则入门 实习email和URL验证

    匹配email地址的正则表达式:w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)* 匹配网址url的正则表达式:[a-za-z]+://[^s]* 下面看一实例 <body onload="f.a.select();"> <?php...2016-11-25
  • PHP正则判断输入是否字母实例程序

    在php中判断是否为纯字母我们可直接使用正则/^[a-zA-Z]$/来验证了,包括大小写字母哦,有需要了解的同学可参考参考。 上代码 代码如下 复制代码 ...2016-11-25
  • C#正则检测字符串是否字母数字混编的方法

    这篇文章主要介绍了C#正则检测字符串是否字母数字混编的方法,涉及C#正则判定字符串的使用技巧,需要的朋友可以参考下...2020-06-25
  • 正则文章内容中img图片地址与正则内容中的a连接地址

    本篇实例主要是讲到关于如何使用php中正则表达试来获取我们想要的东西,上面的实例就是要把文章内容字符串的链接地址与图片地址全部取出来,所有我们要正则就方便多了...2016-11-25
  • php正则链接-取得内容所有链接

    下面提供二款关于php正则链接方法,他们可以-取得内容所有链接并且保存到一个数组,当然也可以把链接全部替换哦。 方法一 代码如下 ...2016-11-25