Table of Contents
{$year}年{$month}月
Home Backend Development PHP Tutorial PHP第九课 正则表达式在PHP中的使用

PHP第九课 正则表达式在PHP中的使用

Jun 23, 2016 pm 01:51 PM
php regular expression

今天内容
1.正则表达式
2.数学函数
3.日期函数
4.错误处理


正则表达式:
1.模式修正符
2.五个常用函数




另外一个正则表达式的网站:http://www.jb51.net/tools/zhengze.html

正则表达式
1.原子
2.元子符
3.模式修正符




正则表达式函数
1.preg_match();
2.preg_match_all();
3.preg_grep();
4.preg_replace();
5.preg_split();




原子:




.:代表任意一个字符
\w: 字母 数字 下划线




元子符:




*:修饰前面的,0,1,多个.代表任意多个字符,直到结束
+:一个.多个
?:0个一个前面的原子
|:代表或
^:一开什么开头
$:以什么结尾
\b:词边缘
\B:非词边缘




单个字母 数字
a-z A-Z 0-9 代表任意一个字符
[]代表里面的任意一个字符
[^abc]他里面除了abc的任意一个字符
()代表一个单元
\d 任意一个数字
\D 任意一个非数字
\w:代表任意一个字母数字下划线
\W:出了字母.数字.下划线意外任意一个字符
\s:空白字符
\S:除了空白字符以外的任意一个字符
{2}:2个原子
{2,}:2个以上的原子
{2,5}: 2-5个前面的原子




模式修正符:
/正则表达式/U




匹配与以上特殊字符同名的普通字符,需要在前面加入/

<?php $sub = "www.baidu.com";		$ptn = '/\w*\.\w*\.\w*/';		//         正则表达式,元数据,返回的数据		preg_match($ptn, $sub,$mats);		echo "<pre class="brush:php;toolbar:false">";		print_r($mats);		echo "
Copy after login
"; ?>






//匹配ip

<?php $str = "my ip is 192.168.10.1sdjlfajdf192.178.39.4la";			 $ptn = '/\d+\.\d+\.\d+\.\d+/';			 			 preg_match_all($ptn, $str,$mats);			 echo "<pre class="brush:php;toolbar:false">";			 print_r($mats);			 echo "
Copy after login
"; ?>


模式修正符,放在正则表达式的最后面


i,m,s,u,e
i :忽略大小写
m :视为多行
s :视为一行
u :贪婪模式,最大模式
e :替换的时候用的,可以用函数加工,用于匹配正则表达式中的第一个圆括号



<?php $str = "Linux and php are lamp or linux is very  much"; $ptn = '/linux/i'; preg_match_all($ptn, $str,$mats); echo "<pre class="brush:php;toolbar:false">"; print_r($mats); echo "
Copy after login
"; ?>



 m例子
 m视为多行
 <?php $str = "Linux and php are lamp or \nlinux is very  much"; $ptn = '/^linux/im'; preg_match_all($ptn, $str,$mats); echo "<pre class="brush:php;toolbar:false">"; print_r($mats); echo "
Copy after login
"; ?>



模式修正符


<?php $str = "Linux and php are lamp or \nlinux is very  much"; $ptn = '/.*/s'; preg_match_all($ptn, $str,$mats); echo "<pre class="brush:php;toolbar:false">"; print_r($mats); echo "
Copy after login
"; ?>





 e的使用
 
<?php $str = "123 php"; $ptn = '/\d+\s(\w+)/e'; $rep = 'strtoupper($1)'; // preg_match_all($ptn, $str,$mats); $str2 = preg_replace($ptn, $rep, $str); echo "<pre class="brush:php;toolbar:false">"; print_r($str2); echo "
Copy after login
"; ?>





向后引用
 <?php $str = "123 php"; $ptn = '/(\d+)(\s)(\w+)/'; $rep = '$3$2$1'; // preg_match_all($ptn, $str,$mats); $str2 = preg_replace($ptn, $rep, $str); echo "<pre class="brush:php;toolbar:false">"; print_r($str2); echo "
Copy after login
"; ?>

 


五个常用函数


1.字符串的匹配与替换
preg_match();
preg_match_all();
preg_grep();做搜索


2.字符串的替换
preg_replace();


3.字符串的分割
preg_split();




eval让字符串表达式能够执行


preg_grep实例,做搜索:
 
<?php //比如代表文章    $arr = array(      "php html",      " linux redhat rhce",      "junzaivip test php",    	);	 //需要搜索的内容    $ptn = '/junzaivip/';    //返回搜索到的内容    $arr2 = preg_grep($ptn, $arr);    echo "<pre class="brush:php;toolbar:false">";    print_r($arr2);    echo "
Copy after login
"; ?>



 4.数学函数
  1.max();
  2.min();


  注意:1.多个数字,2,多个数字组成的数组
   
<?php echo max(3,45,6,7);	 echo "<br>";	 echo max(array(4,6,8,9));	 ?>
Copy after login





5.日期函数
1.time();
2.date(); //把时间戳转换为日期
3.strtotime();//把日期转换为时间戳
4.microtime();
//calc打开计算器


时间的起源点:
 
<?php echo time(); echo "<hr>"; echo date("Y-m-d H:i-s w t",0); ?>
Copy after login


 时间转换为时间戳
 
 <?php echo strtotime("2014-12-12"); ?>
Copy after login





 计算当前时间的具体日期:
  <?php echo date("Y-m-d H:i:s",time()+8*3600); ?>
Copy after login




 通过修改时区来查找当前日期:
  <?php //设置中国的时区为默认时区 date_default_timezone_set("PRC"); echo date("Y-m-d H:i:s",time()); ?>
Copy after login




 注意:如果每个改比较麻烦的话,就直接去修改php的配置文件php.ini文件,直接修改里面的date 找见timezone修改为PRC




 date参数:
 Y 2014  年全
 y 14    年只有后两位
 m 03    月份有前导0
 n 3     月份没有前导0
 d 05 日期有前导0
 j 5     日期没有前导0
 H       24小时
 h       12小时
 i       05分钟 
 s       05秒
 w 0-6   周日到周六
 t 31    一月多少天
 L       是否为闰年


 //怎样区分平润年
 能够被4整除,同时如果能被100整除的话,那就必须被400整除,此时它就是闰年
  
<?php //设置中国的时区为默认时区	 date_default_timezone_set("PRC");	 $y = "1900/1/1";	 $time = strtotime($y);	 echo date("L",$time); ?>
Copy after login




 microtime() 微秒


 计算脚本的运行时间:
  
<?php $stime =  microtime(1);//注意这个位置必须用true,否者无法参与计算 	sleep(1); 	$etime =  microtime(1); 	echo $etime - $stime; ?>
Copy after login




 实例:万年历


 万年历技术点
 1.几年几月几日
 2.周日到周六
 3.1号是星期几
 4.这个月有多少天
 5.下一年和上一年
 6.下一月和上一月


 万年历代码:
  
<?php //修改字符编码 //header("content-type:text/html;charset=utf-8"); date_default_timezone_set("PRC"); 	//获取当前年 $year = $_GET['y']?$_GET['y']:date('Y'); 	//获取当前月 $month = $_GET['m']?$_GET['m']:date('m'); 	//获取获取当前月有多少天 $days =  date('t',strtotime("{$year}-{$month}-1"));//里面必须用双引号 //当前一号是周几 $weeks = date('w',strtotime("{$year}-{$month}-1")); //所有有内容居中 echo "<center>"; //输出表头 echo "<h2 id="year-年-month-月">{$year}年{$month}月</h2>"; //输出日期表格 echo "
Copy after login
"; //输出第一行 echo ""; //表头单元格由th来创建 echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; //开始铺表格 for($i = 1 - $weeks;$i "; for ($j=0; $j $days || $i  "; } else{ echo ""; } $i++; } echo ""; } echo "
{$i}
"; //实现一下上一年和上一月 if($month == 1){ $prevyear = $year - 1; $prevmonth = 12; } else{ $prevyear = $year; $prevmonth = $month -1; } if($month == 12){ $nextyear = $year + 1; $nextmonth = 1; } else{ $nextyear = $year; $nextmonth = $month + 1; } //输出上一月和下一月的按钮 echo "

上一月|下一月

"; echo ""; ?>




PHP的错误处理
1.关闭和开启报错
2.错误报告级别
3.错误报告地方






关闭和开启报错




E_ALL
E_ERROR //严重错误
E_WARNING  //警告错误
E_PARSE    //语法错误
E_NOTICE //提示错误


关闭错误
display_error = off




报什么级别的错:
error_reporting = E_ALL
error_reporting = E_ALL & ~E_NOTICE //报所有错误,但是除了提示错误


报错地方:
//是否从浏览器报错
display_error = off


//是否把错误输出到一个自定义日志文件中
log_errors = on


error_log = d:\phplogs\php.log

转载请注明出处: http://blog.csdn.net/junzaivip



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles