LAMP兄弟连原创视频教程(PHP笔记四--正则表达式,文件,目录操作)

8.1 正则表达式的功能介绍
与正则表达式:是用描述字符排列模式一种语法规则
作用:字符串的模式分割、匹配、查找、替换
正规字符:abcd 13456
特殊字符:() ? ^ $
原子:(普通字符,如:英文字符)单个字符,数字,如a-z,A-Z,0-9
原子表:[abc][^abc]
转义字符:
 /d 匹配一个数字0-9
 /D 匹配除数字以外的一个字符[^0-9]
 /w 匹配一个英文字母,数字或下划线字符[0-9a-zA-Z]
 /W 匹配除一个英文字母,数字或下划线外的一个字符[^0-9a-zA-Z]
 /s 匹配一个空白字符[/f/n/r/t/v]
 /f
 /n
 /r
 /t
 /v
 /oNN
 /xNN
 /cC
元字符:(有特殊功能用途字符)* + ? . | ^ $
* 0,1或多次匹配前面的原子
+ 1或多次匹配前面的原子
? 0或1次 匹配前面的原子
. 匹配除换行符外任何一个字符,相当于[^/n/r]
| 匹配两个或多个选择
^ 匹配字符串串首的原子
$ 匹配字符串串尾的原子
/b 匹配单词的边界
/B 匹配单词的边界以外
{m} 表示其前原子恰好出现m次
{m,n} 表示其前的原子至少出现m次,最多出现n次
{m,} 表示其前的原子出现不少于m次
() 整体表示一个原子观念

模式匹配的顺序 左到右
模式单元 ()
重复匹配 ? * + {} 2
边界限制  ^ $ /b /B 3
模式选择 |

模式修正字符(i,U,s,x...)
标记在整个模式之外 例:/abc/i
i 不区分大小写的匹配
m 将字符串视为多行
s 将字符串视为单行,换行符作为普通字符
x 将模式中的空白忽略
A 强制公从目标字符串的开关开始匹配
U 只匹配到最近字符
S
PHP提供了两种函数库(PCRE preg_,POSIX ereg_)
<?php
$str1=$$_GET["str1"];
$mode="/abc/";

if(preg_match($mode,$str1,$content))
{
 echo "你输入的字符串".$str1."和模式".$mode."匹配成功,匹配出来的字符是".$content;
}else
{
 echo "你输入的字符串".$str1."和模式".$mode."匹配不成功
}
?>

自我学习:搜索常用正则表达式

8.4 正则表达式处理函数
preg_match()
preg_match_all()
preg_replace()
<?php
 $content="当前日期和时间是".date("Y-m-d h:i a").",我们学习php";
 if(preg_match("/(/d{4}-/d{2}-/d{2}) (/d{2}:/d{2}) ([ap]m)/",$content,$m))
 {
  echo "匹配的时间是:".$m[0]."<br>";
  echo "匹配的日期是:".$m[1]."<br>";
  echo "匹配的时间是:".$m[2]."<br>";
  echo "匹配的上下午是:".$m[3]."<br>";
 }else
 {
  echo " 匹配不成功";
 }
?>
<?php
 $arr=array("aaa bbb","abc","hello hello","ffff");
 $brr=preg_grep("/^[a-z]*$/i",$arr);
 print_r($brr);
?>

将网址转为链接
<?php
 $urlstr="你好在http://www.lampbrother.net里面有好多lamp视频,在http://www.phpchina.com有好多 

  php的学习内容,在http://www.uselib.com里面有更多的IT学习内容<br>";
 echo url2html($urlstr);
 function url2html($urlstr)
 {
  preg_match_all("/http:(www/.)?.+/.(com|org|net)/iU",$urlstr,$urls);
  forecah($urls[0] as $url)
  {
   $urlstr=str_replace($url,"<a href=$url>$url</a>",$urlstr);
  }
  return $urlstr;
 }
?>

对时间不同部分设置不同颜色
<?php
 $str="current date and time is".date("Y-m-d h:i a").",we are learning php";
 echo preg_replace("/(/d{r}-/d(2)-/d{2}) (/d{2}:/d{2}) ([ap]m)/","<font  

color=red>//1</font><font color=blue>//2</font><font color=green>//3</font>",$str);
?>
<?php
 $str="名字:{name}<br> email:{email} <br> age:{age}";
 $patterns=array("/{name}/","/{email}/","/{age}/");
 $replacements=array("xiaomo","xx@11.com","22");
 echo preg_replace($patterns,$replacements,$str);
?>

计算段落共有多少句
<?php
 $str="在本周摩根士丹利公司(大摩)发布的一份“互联网趋势”的报告中,腾讯成为唯一的一家被屡次提 

 及的中国公司,在创新能力方面甚至被认为超越了微软,仅次于苹果、谷歌和亚马逊,位居第四";  

$arr=preg_split("/[,。、/s]/", $str);
 foreach($arr as $value)
 {
  echo $value."<br>";
 } 
?>

8.6 正则表达式的实例应用
UBBCode转义
<?php
 $str="[b]你好[/b]<br>
            [i]你好[i/]<br>
            [size=3]你好[/size]<br>
       [font face=宋体]你好[/font]";
 echo $str;
 echo conUbb($str);
 function conUbb($str)
 {
  $pattern=array("//[b/](.+?)/[//b/]/is",
          "//[i/](.+?)/[//i/]/is",
    "//[font=([,/w]x7f-/xff]+?)/](.+?)/[//font/]/");
  $replacements=array("<b>//1</b>",
        "<i>//1</i>",
        <font face='//1'>//2</font>);
  $str1=preg_replace()
 }

?>

9.1文件系统处理
永存保存文件途径:
1.写入文件
2.写入数据库
注意:php对文件系统的操作是基于Unix系统,或者linux
文件一般处理函数
fopen()
<?php
/*
 fopen("目的文件名称","文件打开模式参数")
 目的文件名称
 windows: c://test/test.txt
 linux:  /root.DIRECTORY_SEPAPATOR.test/test.txt
  /root/test/test.txt
 fopen("/home/abc/a.txt","r");
 fopen("c://test/test.txt","r");
 fopen("test.txt","r");
 
 fopen("../rest/test.txt","r");
 
 fopen("http://www.userlib.com/index.php","r");

 fopen("ftp://root:pass@www.userlib.com/a.txt","r")
 
 文件打开模式参数
 r r+(可读写) w (打开文件,先清空,文件不存在时创建文件) w+ a a+(文件不存在时创建文件) x(文件存 

 在返回false,文件不存在创建文件) x+(能读写) b(只限于windows) t(只限于windows)
*/
 $file=fopen("test.txt","w") or die("文件打开失败!");
 for($i=0;i<10;i++)
 {
  fwrite($file,"www.uselib.com$i/n",10);//fputs($file,"www.uselib.com$i/n",10);
 }
 fclose($file) or die("文件关闭失败!");
 var_dump($file);
?>

读取文件

<?php
 $file=fopen("test.txt","r") or die("打开文件失败!");
 //echo fread($file, filesize("test.txt"));
 while(!feof($file))
 {
            $linestr=fgets($file)//从文件指针读取一行
  echo $linestr."<br>";
 }
 fclose($file) or die("关闭文件失败!");
?>
<?php
 $file=fopen("test.txt","r") or die("打开文件失败!"
 while($ch=fgetc($file)!==false)
 {
  echo $ch;
 }
 fclose($file) or die("关闭文件失败");
?>
<?php
 //不用打开关闭文件,直接读取
 $filename="test.txt";
 $lineArr=file($filename);
 foreach($lineArr as $line)
 {
  echo $line."<br>";
 }
?>
<?php
 $file="test.txt";
 readfile($filename);
?>

小应用:
<?php
 //文件计数器
 $counterfile="counter.txt";
 if(!file_exists($counterfile))
 {
  $fw=fopen($counterfile,"w");
  fwrite($fw,0);
  fclose($fw);
 }
 function dip($counterfile)
 {
  $fp=fopen($counterfile,"r");
  $num=fread($fp,8);
  fclose($fp);
  $num+=1;
  echo "你是本站的第".$num."位游客!";
  $fpw=fopen("$counterfile","w");
  fwrite($fpw,$num);
  fclose($fpw);
 }
 disp($cunterfile);
?>


<?php
 //读取远程的数据
 $file=fopen("http://www.uselib.com/index.php","r");
 $data="";
 while(!feof($file))
 {
  $data.=fgets($file,1024);
 }
 preg_match_all("/<title>,+?</tilte>/",$data,$arr);
 echo $arr[0][0];
?>

 

<?php
 //不用打开就可以读取,也可以读取远程文件
 echo file_get_contents("test.txt");
 //不用打开就可以写入
        file_put_contents("hello.txt","www.userlib.com");
?>

常用运用:读写文件时,对文件进行加锁,防止读写时发生不可意料的错误
<?php
/*
 * LOCK_SN:共享锁定,读文件的时候使用
 * LOCK_EX:独占锁定,写入文件的时候使用
 * LOCK_UN:释放锁定
 * LOCK_NB:附加锁定,不希望锁定阻塞时使用(LOCK_EX+LOCK_NB)
 *
 */
 $file=fopen("text.txt","r");
 if(!flock($file,LOCK_SH))
 {
  die("无法锁定文件");
 }
 echo fread($file,filesize("test.txt"));
 if(!flock($file,LOCK_UN))
 {
  die("无法释放锁定文件");
 }
 fclose($file);
?>

文件指针

ftell() 返回当前位置指针
fseek(文件指针,移动的字节数,起始位置)SEEK_CUR 当前位置SEEK_SET 开始位置 SEEK_END
copy() 复制文件
unlink() 删除文件
rename() 重命名文件
ftruncate()截取文件
<?php
 $file=fopen("test.txt","r");
 echo fread($file,100);
 echo ftell($file)
 fseek($file,30.SEEK_CUR);
 echo ftell($file);
 rewind($file);
 echo ftell($file); 
?>
<?php
 if(copy("test.txt","c://hello.txt"))
 {
  echo "cp ok !!!<br>";
 }else
 {
  echo "cp error!!!<br>";
 }

 if(unlink("c://hello.txt"))
 {
  echo "del success!!!";

 }else
 {
  echo "del error!!!";
 }

 if(rename("text.txt","中国.txt"))
 {
  echo "rename ok";
 }else
 {
  echo "rename error";
 }
 $fp=fopen("text.txt","r+");
 if(ftruncate($fp.10))
 {
  echo "truncate 0k ...";
 }else
 {
  echo "truncate erroe ...";
 }
 fclose($fp);
?>

获取文件属性
filectime();
filemtime();
fileatime();
file_exists();
filesize();
filetype();
is_dir();
is_file();
is_link();
is_executable();
is_readable();
is_writable();


<?php
 $filename="test.txt";
 if(file_exists($filename))
 {
  if(is_file($filename))
  {
   echo $filename."是一个常规文件<br>";
  }
  echo "文件形态".filetype($filename)."<br>";
  echo "文件建立时间".date("Y年m月j日",filectime($filename))."<br>";

 }else
 {
  echo "目标文件不存在";
 }
 //修改文件属性 r->4,w->2,x->1
 if(chmod($filename,644))
 {
  echo "chmode change ok"<br>;
 }else
 {
  echo ""
 }
 //修改文件拥有者
  chown($filename,501);
 //修改文件拥有组
 chgrp($filename,502);
 //获取文件的拥有者
 echo fileowner($filename);
 echo filegroup($filename);
?>

9.6 文件处理之目录操作

opendir(目标路径) readdir(目录引用句柄) closedir()
检索目录 可使用通配符:? * {}
建立目录 mkdir($pathname [,mode])
删除目录
复制目录
<?php

/*

 *遍历目录

 */
 $dirHandle=@opendir("c://AppServ/phpMyAdmin") or die("打开目录失败!!!");
 echo "phpMyAdmin 目录下所有内容是:<br>";
 echo readdir($dirHandle)."<br>";//当前目录
 echo readdir($dirHandle)."<br>";//上级目录


 while(($file=readdir($dirHandle))!==false)
 {
  if(is_dir("c://AppServ/phpMyAdmin"."/".$file))
  {
   echo "目录:".$file."<br>";
  }else
  {
   echo "文件:".$file."<br>";
  }
 }
 rewinddir();//把文件指针移动到开始位置

 while(($file=readdir($dirHandle))!==false)
 {
  if($file!="."&&$file!="..")
   {
   if(is_dir("c://AppServ/phpMyAdmin"."/".$file))
   {
    echo "目录:".$file."<br>";
   }else
   {
    echo "文件:".$file."<br>";
   }
  }
 }
 closedir($dirHandle);
?>
<?php

//遍历文件夹文件
 $d=dir("phpMyAdmin");
 echo "路径是".$d->path."<br>";
 echo "引用句柄是:".$d->handle."<br>";
 while(($file=$d->read())!==fale)
 {
  if(file!="."&&file!="..")
  {
   echo $file."<br>";
  }
 }
 $d->close();
?>


<?php 
 //检索目录
 //$fileArr=glob("phpMyAdmin/{c,d}*",GLOB_BRAGE);
 $fileArr=glob("phpMyAdmin/*",GLOB_ONLYDIR);
 foreach($fileArr as $file)
 {
  echo $file."<br>";
 }
?>


<?php
 if(mkdir("xxxx",0700))
 {
  echo "目录建立成功";
 }else
 {
  echo "目录建立失败"; 
 }
?>

删除目录(PHP中只提供删除空目录的函数,以下函数能对非空目录进行删除)
<?php
 $file="xxxx";
 function(delteDir($pathName))
 {
  $handle=opendir($pathName);
  readdir($handle);
  readdir($handle);
  while($file=readdir($handle))!=false
  {
   $file=$path.DIRCTORY_SEPAAATOR.$file;
   if(is_dir($file))
   {
    deleteDir($file);
   }else
   {
    if(unlink($file))
    {
     echo "文件 $file 删除成功<br>";
    }else
    {
     echo "文件 $file 删除失败<br>";
    }
   }
  }
  closedir($handle);
  if(rmdir($pathName))
  {
    echo "目录<b>$pathName</b>删除成功<br>";
  }else
  {
   echo "目录<b>$pathName</b>删除失败<br>";
  }
  
 }
 deleteDir($file);
?>

拷贝目录
<?php
 $filecounter=0;
 $dircounter=0;
 function  copydir($dirFrom,$dirTo)
 { 
  global $filecounter;
  global $dircounter;
  if(is_file($dirTo))
  {
   die("无法创建目录 $dirTo");
  }
  if(file_exists($dirTo))
  {
   mkdir($dirTo);
   $dircounter++;
  }
  $handle=opendir($dirFrom);
  
  readdir($handle);
  readdir($handle);

  while($file=readdir($handle)!=false)
  {
   $fileFrom=$dirFrom.DIRCTORY_SEPAAATOR.$file;
   $fileTo=$dirTo.DIRCTORY_SEPAAATOR.$file;
   if(is_dir($fileFrom))
   {
    copyDir($fileFrom,$fileTo);
   }else
   {
    copy($fileFrom,$fileTo);
    $filecounter++;
   }
   
  }
  closeDir($handle);
 }
 
 copydir("phpMydmin","phpAdmin");
 echo "共拷贝文件 $filecounter 个<br>";
 echo "共拷贝目录 $dircounter 个<br>";

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值