search
HomeBackend DevelopmentPHP TutorialDetailed explanation of commonly used functions in PHP regular expressions

Detailed explanation of commonly used functions in PHP regular expressions

Nov 11, 2017 pm 01:16 PM
phpexpressionDetailed explanation

In the previous articles, we learned the use of php regular expressions and getting started. Today we will focus on introducing the common functions of php regular expressions, both It can be used perfectly when combined! !

1. preg_match()

Function prototype:

int preg_match (string $pattern, string $content [, array $matches])

preg_match () function searches the $content string for content that matches the regular expression given by $pattern. If $matches is provided, the matching results are placed in it. $matches[0] will contain the text that matches the entire pattern, $matches[1] will contain the first captured match of the pattern element enclosed in parentheses, and so on. This function only performs one match and ultimately returns the number of matching results of 0 or 1. Listing 6.1 shows a code example for the preg_match() function.
Code 6.1 Date and time matching
The code is as follows:

<?php 
//需要匹配的字符串。date函数返回当前时间 
$content = "Current date and time is ".date("Y-m-d h:i a").", we are learning PHP together."; 
//使用通常的方法匹配时间 
if (preg_match ("//d{4}-/d{2}-/d{2} /d{2}:/d{2} [ap]m/", $content, $m)) 
{ 
echo "匹配的时间是:" .$m[0]. "/n"; 
} 
//由于时间的模式明显,也可以简单的匹配 
if (preg_match ("/([/d-]{10}) ([/d:]{5} [ap]m)/", $content, $m)) 
{ 
echo "当前日期是:" .$m[1]. "/n"; 
echo "当前时间是:" .$m[2]. "/n"; 
} 
?>

This is a simple dynamic text string matching example. Assuming that the current system time is "13:25 on August 17, 2006", the following content will be output.
The matching time is: 2006-08-17 01:25 pm
The current date is: 2006-08-17
The current time is: 01:25 pm

2 . ereg() and eregi()

ereg() is the matching function for regular expressions in the POSIX extension library. eregi() is a case-ignoring version of the ereg() function. Both have similar functions to preg_match, but the function returns a Boolean value indicating whether the match was successful or not. It should be noted that the first parameter of the POSIX extension library function accepts a regular expression string, that is, no delimiter is required. For example, Listing 6.2 is a method for checking the security of file names.
Code 6.2 Security check of file name
The code is as follows:


##

<?php 
$username = $_SERVER[&#39;REMOTE_USER&#39;]; 
$filename = $_GET[&#39;file&#39;]; 
//对文件名进行过滤,以保证系统安全 
if (!ereg(&#39;^[^./][^/]*$&#39;, $userfile)) 
{ 
die(&#39;这不是一个非法的文件名!&#39;); 
} 
//对用户名进行过滤 
if (!ereg(&#39;^[^./][^/]*$&#39;, $username)) 
{ 
die(&#39;这不是一个无效的用户名&#39;); 
} 
//通过安全过滤,拼合文件路径 
$thefile = "/home/$username/$filename"; 
?>


Normally, use The Perl-compatible regular expression matching function perg_match() will be faster than using ereg() or eregi(). If you just want to find whether a string contains a certain substring, it is recommended to use the strstr() or strpos() function.

Replacement of regular expressions

1. ereg_replace() and eregi_replace()

Function prototype:

string ereg_replace (string $pattern, string $replacement, string $string) 
string eregi_replace (string $pattern, string $replacement, string $string)

ereg_replace() searches for the pattern string $pattern in $string and replaces the matched result with $replacement. When $pattern contains pattern units (or sub-patterns), positions in $replacement such as "/1" or "$1" will be replaced by the content matched by these sub-patterns. And "/0" or "$0" refers to the content of the entire matching string. It should be noted that the backslash is used as an escape character in double quotes, so the form "//0" and "//1" must be used.

eregi_replace() and ereg_replace() have the same functions, except that the former ignores case. Code 6.6 is an application example of this function. This code demonstrates how to do simple cleaning work on the program source code.
Code 6.6 Cleaning up the source code
The code is as follows:

<?php 
$lines = file(&#39;source.php&#39;); //将文件读入数组中 
for($i=0; $i<count($lines); $i++) 
{ 
//将行末以“//”或“#”开头的注释去掉 
$lines[$i] = eregi_replace("(////|#).*$", "", $lines[$i]); 
//将行末的空白消除 
$lines[$i] = eregi_replace("[ /n/r/t/v/f]*$", "/r/n", $lines[$i]); 
} 
//整理后输出到页面 
echo htmlspecialchars(join("",$lines)); 
?>


2. preg_replace()

Function prototype:

mixed preg_replace (mixed $pattern, mixed $replacement, mixed $subject [, int $limit])

preg_replace is more powerful than ereg_replace. The first three parameters can all use arrays; the fourth parameter $limit can set the number of replacements, and the default is to replace all. Code 6.7 is an application example of array replacement.

Code 6.7 Array replacement
The code is as follows:


<?php 
//字符串 
$string = "Name: {Name}<br>/nEmail: {Email}<br>/nAddress: {Address}<br>/n"; 
//模式 
$patterns =array( 
"/{Address}/", 
"/{Name}/", 
"/{Email}/" 
); 
//替换字串 
$replacements = array ( 
"No.5, Wilson St., New York, U.S.A", 
"Thomas Ching", 
"tom@emailaddress.com", 
); 
//输出模式替换结果 
print preg_replace($patterns, $replacements, $string); 
?>

The output results are as follows.

Name: Thomas Ching", 
Email: tom@emailaddress.com 
Address: No.5, Wilson St., New York, U.S.A

The pattern modifier "e" can be used in the regular expression of preg_replace. Its function is to use the matching result as an expression and can be re-operated. For example:

The code is as follows:

<?php 
$html_body = “<HTML><Body><h1 id="TEST">TEST</h1>My Picture<Img src=”my.gif”></Body></HTML>”; 
//输出结果中HTML标签将全部为小写字母 
echo preg_replace ( 
"/(<//?)(/w+)([^>]*>)/e", 
"&#39;//1&#39;.strtolower(&#39;//2&#39;).&#39;//3&#39;", //此处的模式变量//2将被strtolower转换为小写字符 
$html_body); 
?>

Summary:

preg_replace function uses Perl-compatible regular expression syntax, which is usually better than ereg_replace Faster alternative. If you only want to do a simple replacement of a string, you can use the

str_replace function.

Related recommendations:

Detailed explanation of preg_match_all function in php regular expressions


Detailed explanation of preg_match function in php regular expression


A case of php regular expression to verify email address


Instance analysis of php regular expressions


Detailed introduction to php regular expressions

The above is the detailed content of Detailed explanation of commonly used functions in PHP regular expressions. For more information, please follow other related articles on the PHP Chinese website!

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

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.

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

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software