


Detailed explanation of commonly used functions in PHP regular expressions
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['REMOTE_USER']; $filename = $_GET['file']; //对文件名进行过滤,以保证系统安全 if (!ereg('^[^./][^/]*$', $userfile)) { die('这不是一个非法的文件名!'); } //对用户名进行过滤 if (!ereg('^[^./][^/]*$', $username)) { die('这不是一个无效的用户名'); } //通过安全过滤,拼合文件路径 $thefile = "/home/$username/$filename"; ?>
1. ereg_replace() and eregi_replace()
string ereg_replace (string $pattern, string $replacement, string $string) string eregi_replace (string $pattern, string $replacement, string $string)
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('source.php'); //将文件读入数组中 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()
mixed preg_replace (mixed $pattern, mixed $replacement, mixed $subject [, int $limit])
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); ?>
Name: Thomas Ching", Email: tom@emailaddress.com Address: No.5, Wilson St., New York, U.S.A
The code is as follows:
<?php $html_body = “<HTML><Body><H1>TEST</H1>My Picture<Img src=”my.gif”></Body></HTML>”; //输出结果中HTML标签将全部为小写字母 echo preg_replace ( "/(<//?)(/w+)([^>]*>)/e", "'//1'.strtolower('//2').'//3'", //此处的模式变量//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 thestr_replace function.
Related recommendations:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

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,

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

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

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 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.
