search
HomeBackend DevelopmentPHP TutorialPHP第九课 正则表达式在PHP中的使用

今天内容
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 "
"; ?>






//匹配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 "
"; ?>


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


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 "
"; ?>



 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 "
"; ?>



模式修正符


<?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 "
"; ?>





 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 "
"; ?>





向后引用
 <?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 "
"; ?>

 


五个常用函数


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 "
"; ?>



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


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





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); ?>


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





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




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




 注意:如果每个改比较麻烦的话,就直接去修改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); ?>




 microtime() 微秒


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




 实例:万年历


 万年历技术点
 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 "
"; //输出第一行 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
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
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function