php正则修正符用法实例介绍

 更新时间:2016年12月31日 09:44  点击:1850
这篇文章介绍了php的正则修正符,非常具有学习价值,有兴趣的同学可以参考一下

本文实例讲述了php正则修正符用法。分享给大家供大家参考,具体如下:

 
 代码如下 复制代码
<?php
   //标记在整个模式之外;
   // 例://$mode="/\bis\b/U",其中U在外面;
  //修正符:i 不区分大小写的匹配;
     //如:"/abc/i"可以与abc或aBC或ABc等匹配;
  //修正符:m 将字符串视为多行,不管是那行都能匹配;
  //  例://模式为:$mode="/abc/m";
     //要匹配的字符串为:$str="bcefg5e\nabcdfe"
     //注意其中\n,换行了;abc换到了下一行;
     //$str和$mode仍可以匹配,修正符m使得多行也可匹配;
  //修正符:s 将字符串视为单行,换行符作为普通字符;
   // 例://模式为:$mode="/pr.y/";
      //要匹配字符串为:$str="pr\ny";
      //两者不可匹配; . 是除了换行以外的字符可匹配;
      //修改下模式为:$mode="/pr.y/s";
        //其中修正符s将\n视为普通字符,即不是换行;
      //最后两者可以匹配;
  //修正符:x 将模式中的空白忽略;
  //修正符:A 强制从目标字符串开头匹配;
   // 例://$mode="/abc/A";
      //可以与$str="abcsdfi"匹配,
      //不可以与$str2="sdsdabc"匹配;
      //因为$str2不是以abc开头;
  //修正符:D 如果使用$限制结尾字符,则不允许结尾有换行;
  //  例://模式为:$mode="/abc$/";
      //可以与最后有换行的$str="adshabc\n"匹配;
      //元子符$会忽略最后的换行\n;
      //如果模式为:$mode="/abc/D",
      //则不能与$str="adshabc\n"匹配,
      //修正符D限制其不可有换行;必需以abc结尾;
  //修正符:U 只匹配最近的一个字符串;不重复匹配;
  //  例:
  //   如模式为:
      $mode="/a.*c/";
      $str="abcabbbcabbbbbc";
      preg_match($mode,$str,$content);
      echo$content[0];//输出:abcabbbcabbbbbc;
      //如果$mode="/a.*c/";变成$mode="/a.*c/U";
      // 则只匹配最近一个字符串,输出:abc;
//修正符:e 配合函数preg_replace()使用,
//      可以把匹配来的字符串当作正则表达式执行;
?>
 

修正符:

POSIX兼容正则没有修正符。

PERL兼容正则中可能使用的修正符(修正符中的空格和换行被忽略,其它字符会导致错误):

i(PCRE_CASELESS):
匹配时忽略大小写。

m(PCRE_MULTILINE):
当 设定了此修正符,行起始(^)和行结束($)除了匹配整个字符串开头和结束外,还分别匹配其中的换行符(\n)的之后和之前。

s(PCRE_DOTALL):
如 果设定了此修正符,模式中的圆点元字符(.)匹配所有的字符,包括换行符。没有此设定的话,则不包括换行符。

x(PCRE_EXTENDED):
如 果设定了此修正符,模式中的空白字符除了被转义的或在字符类中的以外完全被忽略。

e:
如果设 定了此修正符,preg_replace() 在替换字符串中对逆向引用作正常的替换,将其作为 PHP 代码求值,并用其结果来替换所搜索的字符串。 只有 preg_replace() 使用此修正符,其它 PCRE 函数将忽略之。

A(PCRE_ANCHORED):
如 果设定了此修正符,模式被强制为“anchored”,即强制仅从目标字符串的开头开始匹配。

D(PCRE_DOLLAR_ENDONLY):
如 果设定了此修正符,模式中的行结束($)仅匹配目标字符串的结尾。没有此选项时,如果最后一个字符是换行符的话,也会被匹配在里面。如果设定了 m 修正符则忽略此选项。

S:
当一个模式将被使用若干次时,为加速匹配起见值得先对其进行分析。 如果设定了此修正符则会进行额外的分析。目前,分析一个模式仅对没有单一固定起始字符的 non-anchored 模式有用。

U(PCRE_UNGREEDY):
使 “?”的默认匹配成为贪婪状态的。

X(PCRE_EXTRA):
模式中的任何反斜线后面跟上 一个没有特殊意义的字母导致一个错误,从而保留此组合以备将来扩充。默认情况下,一个反斜线后面跟一个没有特殊意义的字母被当成该字母本身。

u(PCRE_UTF8):
模 式字符串被当成UTF-8。

注意:

     模式修正符(Pattern Modifiers)

i     -可同时匹配大小写字母
M     -将字符串视为多行
S     -将字符串视为单行,换行符做普通字符看待,使“.”匹配任何字符
X     -模式中的空白忽略不计
U     -匹配到最近的字符串
e     -将替换的字符串作为表达使用

这篇文章讲述了php中如何实现文件操作类及文件下载功能的教程,非常有用,感兴趣的同学可以参考一下

本文实例讲述了PHP实现的文件操作类及文件下载功能。分享给大家供大家参考,具体如下:

文件操作类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
<?php
 // Copyright 2005, Lee Babin (lee@thecodeshoppe.com)
 // This code may be used and redistributed without charge
 // under the terms of the GNU General Public
 // License version 2.0 or later -- www.gnu.org
 // Subject to the retention of this copyright
 // and GPL Notice in all copies or derived works
 classcfile {
  //The path to the file we wish to work with.
  protected$thepath;
  //Error messages in the form of constants for ease of use.
  constFOUNDERROR ="Sorry, the file in question does not exist.";
  constPERMERROR ="Sorry, you do not have the proper permissions on this file";
  constOPENERROR ="Sorry, the file in question could not be opened.";
  constCLOSEERROR ="Sorry, the file could not be closed.";
  //The constructor function.
  publicfunction__construct (){
   $num_args= func_num_args();
   if($num_args> 0){
    $args= func_get_args();
    $this->thepath =$args[0];
   }
  }
  //A function to open the file.
  privatefunctionopenfile ($readorwrite){
    //First, ensure the file exists.
    try{
      if(file_exists($this->thepath)){
        //Now, we need to see if we are reading or writing or both.
        $proceed= false;
        if($readorwrite=="r"){
          if(is_readable($this->thepath)){
            $proceed= true;
          }
        }elseif($readorwrite=="w"){
          if(is_writable($this->thepath)){
            $proceed= true;
          }
        }else{
          if(is_readable($this->thepath) &&is_writable($this->thepath)){
            $proceed= true;
          }
        }
        try{
          if($proceed){
            //We can now attempt to open the file.
            try{
              if($filepointer=fopen($this->thepath,$readorwrite)){
                return$filepointer;
              }else{
                thrownewexception (self::OPENERROR);
                returnfalse;
              }
            }catch(exception$e) {
              echo$e->getmessage();
            }
          }else{
            thrownewexception (self::PERMERROR);
          }
        }catch(exception$e) {
          echo$e->getmessage();
        }
      }else{
        thrownewexception (self::FOUNDERROR);
      }
    }catch(exception$e) {
      echo$e->getmessage();
    }
  }
  //A function to close a file.
  functionclosefile () {
    try{
      if(!fclose ($this->thepath)){
        thrownewexception (self::CLOSEERROR);
      }
    }catch(exception$e) {
      echo$e->getmessage();
    }
  }
  //A function to read a file, then return the results of the read in a string.
  publicfunctionread () {
    //First, attempt to open the file.
    $filepointer=$this->openfile ("r");
    //Now, return a string with the read data.
    if($filepointer!= false){
      //Then we can read the file.
      returnfgets($filepointer);
    }
    //Lastly, close the file.
    $this->closefile ();
  }
  //A function to write to a file.
  publicfunctionwrite ($towrite) {
    //First, attempt to open the file.
    $filepointer=$this->openfile ("w");
    //Now, return a string with the read data.
    if($filepointer!= false){
      //Then we can read the file.
      returnfwrite ($filepointer,$towrite);
    }
    //Lastly, close the file.
    $this->closefile ();
  }
  //A function to append to a file.
  publicfunctionappend ($toappend) {
    //First, attempt to open the file.
    $filepointer=$this->openfile ("a");
    //Now, return a string with the read data.
    if($filepointer!= false){
      //Then we can read the file.
      returnfwrite ($filepointer,$toappend);
    }
    //Lastly, close the file.
    $this->closefile ();
  }
  //A function to set the path to a new file.
  publicfunctionsetpath ($newpath) {
    $this->thepath =$newpath;
  }
 }
?>
1
2
3
4
5
6
7
8
9
<?php
  $myfile=newcfile ("test.txt");
  //Now, let's try reading it.
  echo$myfile->read();
  //Then let's try writing to the file.
  $myfile->write ("Hello World!");
  //Then, let's try appending.
  $myfile->append ("Hello Again!");
?>

文件下载:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
$filename='file1.txt';
$file=fopen($filename,'r');
Header("Expires: 0");
Header("Pragma: public");
Header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
Header("Cache-Control: public");
Header("Content-Length: ".filesize($filename));
Header("Content-Type: application/octet-stream");
Header("Content-Disposition: attachment; filename=".$filename);
readfile($filename);
?>
这篇文章介绍了php文件与目录的操作,是php非常重要的知识点,感兴趣的同学可以参考一下

本文实例讲述了PHP文件与目录操作。分享给大家供大家参考,具体如下:

文件目录相关函数

<?php
// 输出目录中的文件
functionoutputcurfiles ($allowedtypes,$thedir){
//首先,我们确保目录存在。
if(is_dir($thedir)){
 //现在,我们使用scandir扫描目录中的文件。
 $scanarray= scandir ($thedir);
 //接着我们开始解析数组。
 //scandir()用“.”和“..”统计文件导航列表
 //因此作为文件,我们不应该列出他们。
 for($i= 0;$i<count($scanarray);$i++){
  if($scanarray[$i] !="."&&$scanarray[$i] !=".."){
   //现在,进行检查,以确保这是一个文件,而不是一个目录。
   if(is_file($thedir."/".$scanarray[$i])){
    //现在,因为我们将允许客户端编辑这个文件,
    //我们必须检查它是否是可读和可写。
    if(is_writable($thedir."/".$scanarray[$i]) && is_readable($thedir."/".$scanarray[$i])){
     //现在,我们检查文件类型是否存在于允许的类型数组中.
     $thepath=pathinfo($thedir."/".$scanarray[$i]);
     if(in_array ($thepath['extension'],$allowedtypes)){
      //如果文件符合规定,我们可以继续输出.
      echo$scanarray[$i] ."<br />";
     }
    }
   }
  }
 }
}else{
 echo"对不起,这个目录不存在.";
}
}
$allowedtypes=array("txt","html");
outputcurfiles ($allowedtypes,"testfolder");
///////////////////////////////////////////////////
functionrecurdir ($thedir) {
  //First attempt to open the directory.
  try{
    if($adir= opendir ($thedir)){
      //扫描目录。
      while(false !== ($anitem= readdir ($adir))){
        //不统计目录中包含“.”或“..”的情况
        if($anitem!="."&&$anitem!=".."){
          //此时如果是一个目录,则缩进一点
          //再去递归
          if(is_dir($thedir."/".$anitem)){
            ?><span style="font-weight: bold;"mce_style="font-weight: bold;"><?phpecho$anitem; ?></span><?php
            ?><div style="margin-left: 10px;"mce_style="margin-left:10px;"><?php
            recurdir ($thedir."/".$anitem);
            ?></div><?php
          }elseif(is_file($thedir."/".$anitem)){
            //此时输出文件.
            echo$anitem."<br />";
          }
        }
      }
    }else{
      thrownewexception ("Sorry, directory could not be openend.");
    }
  }catch(exception$e) {
    echo$e->getmessage();
  }
}
echo"<br />/////////////////////////////////////<br /><br />";
recurdir("testfolder");
//////////////////////////////////////////////////////////////////
echo"<br />/////////////////////////////////////<br /><br />";
functionsortfilesbydate ($thedir){
  //首先,需要确保目录存在。
  if(is_dir($thedir)){
    //接着,我们使用scandir扫描此目录中的文件.
    $scanarray= scandir ($thedir);
    $finalarray=array();
    //然后开始解析数组
    //scandir()用“.”和“..”统计文件导航列表
    //因此作为文件,我们不应该列出他们.
    for($i= 0;$i<count($scanarray);$i++){
      if($scanarray[$i] !="."&&$scanarray[$i] !=".."){
        //现在,我们检查,以确保这是一个文件,而不是一个目录.
        if(is_file($thedir."/".$scanarray[$i])){
          //现在需要做的是循环数据到一个关联数组.
          $finalarray[$thedir."/".$scanarray[$i]] =filemtime($thedir."/".$scanarray[$i]);
        }
      }
    }
    //至此,我们已经遍历了整个数组,现在需要做的只是asort()它。
    asort ($finalarray);
    return($finalarray);
  }else{
    echo"对不起,这个目录不存在.";
  }
}
//然后,我们将函数指向我们需要查看的目录.
$sortedarray= sortfilesbydate ("testfolder");
//至此,就可以按照如下形式输出:
while($element= each ($sortedarray)){
  echo"File: ".$element['key'] ." was last modified: ".date("F j, Y h:i:s",$element['value']) ."<br />";
}
?>
这篇文章介绍了php中的数组操作,有添加,删除,计算,反转,排序,查找等等。有需要的同学可以参考一下

本文实例分析了PHP数组操作。分享给大家供大家参考,具体如下:

PHP的数组是很重要的一部分。操作示例如下:

<?php
functionbr() {
  echo'<br />===============================================<br />';
}
$arr1=array();
$arr1[] ='x';
$arr1[] ='a';
$arr1[] ='e';
$arr1[] ='c';
$arr1[] ='h';
// 添加数组
array_push($arr1, 3, 23, 55);
// 数组长度
echo'the size of array is :'.count($arr1).'<br />';
// 反转
var_dump(array_reverse($arr1));
// 排序 - 直接作用于数组
sort($arr1);
var_dump($arr1);
// 排序 - 按字符串排序
sort($arr1, SORT_STRING);
var_dump($arr1);
// 范围
$arr2= range('a','h');
// 连接
$arrTemp1= implode('-',$arr2);
echo$arrTemp1;
echo'<br />';
// 切割
echo'['.implode('][',array_reverse(explode('-',$arrTemp1) )).']';
// 数组合并,会重排索引
$arr3=array_merge($arr1,$arr2);
var_dump($arr3);
// 删除数组元素
array_shift($arr3);
array_pop($arr3);
unset($arr3[4]);
array_splice($arr3, 6, 2);
var_dump($arr3);
// 抽取数组,原数组不变
$arr4=array_slice($arr3, 2,3);
var_dump($arr4);
// 关联数组
$fruits=array('red'=>'apple','yellow'=>'banana','green'=>'lime');
// 数组键
$colors=array_keys($fruits);
// 数组值
$fla=array_values($fruits);
var_dump($colors);
var_dump($fla);
// 查找
echoin_array('green',$colors);
echo'<br />';
echoin_array('black',$colors)?'in':'not in';
echo'<br />';
echoarray_key_exists('yellow',$fruits);
echo'<br />';
// 按键排序
ksort($fruits);
var_dump($fruits);
// 按值排序
asort($fruits);
var_dump($fruits);
// 循环
foreach($fruitsas$key=>$value) {
  echo$key.' => '.$value.'<br />';
}
echo'<br />';
$f=$fruits;
while($elem= each($f)) {
  echo$elem['key'].' -- '.$elem['value'].'<br />';
}
echo'<br />';
$arr5=array(2, 8, 100, 33, -18);
// 查找最大最小值
echomax($arr5);
echo'<br />';
echomin($arr5);
echo'<br />';
echoarray_sum($arr5);
echo'<br />';
functiondouble($x) {
  echo($x* 2).' ';
}
// 数组元素应用函数
array_walk($arr5,'double');
functioncheck($x) {
  return$x> 20;
}
// 筛选
var_dump(array_filter($arr5,'check'));
$arr6= range(1,10);
echo'random number: '.array_rand($arr6);
//统计
//count(); sizeof(); array_count_values();
$arr7=array(4,5,1,2,3,1,2,1);
$ac=array_count_values($arr7);
// 统计每个value出现的次数
var_dump($ac);
$arr8=array('key1'=>'v1','key2'=>'v2','key3'=>'v3');
extract($arr8);
echo"$key1 $key2 $key3";
//填补
$input=array(12,10,9);
var_dump(array_pad($input, 5, 0));
var_dump(array_pad($input, -5, 0));
?>
[!--infotagslink--]

相关文章

  • C#中using的三种用法

    using 指令有两个用途: 允许在命名空间中使用类型,以便您不必限定在该命名空间中使用的类型。 为命名空间创建别名。 using 关键字还用来创建 using 语句 定义一个范围,将在此...2020-06-25
  • 一个关于JS正则匹配的踩坑记录

    这篇文章主要给大家介绍了一个关于JS正则匹配的踩坑记录,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-04-13
  • 浅析Promise的介绍及基本用法

    Promise是异步编程的一种解决方案,在ES6中Promise被列为了正式规范,统一了用法,原生提供了Promise对象。接下来通过本文给大家介绍Promise的介绍及基本用法,感兴趣的朋友一起看看吧...2021-10-21
  • iscroll.js 用法介绍

    最新版下载: http://www.csdn123.com/uploadfile/2015/0428/20150428062734485.zip 概要 iScroll 4 这个版本完全重写了iScroll这个框架的原始代码。这个项目的产生...2016-05-19
  • JS基于正则截取替换特定字符之间字符串操作示例

    这篇文章主要介绍了JS基于正则截取替换特定字符之间字符串操作方法,结合具体实例形式分析了JS基于正则实现针对特殊字符、数字等字符串类型的截取操作相关技巧,需要的朋友可以参考下...2017-02-08
  • C#中的try catch finally用法分析

    这篇文章主要介绍了C#中的try catch finally用法,以实例形式分析了try catch finally针对错误处理时的不同用法,具有一定的参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • C++中cin的用法详细

    这篇文章主要介绍了C++中cin的用法详细,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-04-25
  • 示例详解react中useState的用法

    useState 通过在函数组件里调用它来给组件添加一些内部 state,React 会在重复渲染时保留这个 state,接下来通过一个示例来看看怎么使用 useState吧...2021-06-04
  • js正则学习小记之匹配字符串字面量

    关于匹配字符串问题,有很多种类型,今天讨论 js 代码里的字符串匹配,因为我想学完之后写个语法高亮练手,所以用js代码当作例子...2021-05-07
  • Delphi常用关键字用法详解

    这篇文章主要介绍了Delphi常用关键字用法,包括了各个常用的关键字及其详细用法,需要的朋友可以参考下...2020-06-30
  • PHP中print_r、var_export、var_dump用法介绍

    文章详细的介绍了关于PHP中print_r、var_export、var_dump区别比较以及这几个在php不同的应用中的用法,有需要的朋友可以参考一下 可以看出print_r跟var_export都...2016-11-25
  • php中php://input的用法详细

    在使用xml-rpc的时候,server端获取client数据,主要是通过php输入流input,而不是$_POST数组。所以,这里主要探讨php输入流php://input。 下面的例子摘取的是wordpres...2016-11-25
  • C#使用正则表达式过滤html标签

    最近在开发一个项目,其中有需求要求我们把一段html转换为一般文本返回,使用正则表达式是明智的选择,下面小编给介绍下C#使用正则表达式过滤html标签,需要的朋友参考下...2020-06-25
  • js 正则学习小记之匹配字符串字面量优化篇

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

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

    下面我们来看一篇关于Framewrok7 视图介绍(views、view)使用介绍吧,希望这篇文章能够帮助到各位朋友。 一、Views 与View的介绍 1,Views (<div class="views">) (1)Vi...2016-10-02
  • MySQL中的主键以及设置其自增的用法教程

    1、声明主键的方法: 您可以在创建表的时候就为表加上主键,如: CREATE TABLE tbl_name ([字段描述省略...], PRIMARY KEY(index_col_name)); 也可以更新表结构时为表加上主键,如: ALTER TABLE tbl_name ADD PRIMARY KEY (in...2015-11-24
  • C#中this的用法集锦

    本文给大家汇总介绍了C#中的几种this用法,相信大家应该有用过,但你用过几种?以下是个人总结的this几种用法,欢迎大家拍砖,废话少说,直接列出用法及相关代码。...2020-06-25
  • OpenResty中正则模式匹配的2种方法详解

    在 OpenResty 中,同时存在两套正则表达式规范:Lua 语言的规范和 Nginx 的规范,下面这篇文章主要给大家介绍了关于OpenResty中正则模式匹配的2种方法,文中通过示例代码介绍的非常详细,需要的朋友可以参考下。...2020-06-30
  • window.onerror()的用法与实例分析

    目前在做window.onerror时上报js错误信息的事,整理下相关资料,需要的朋友可以参考下...2016-01-29