


PHP regular expression commonly used functions, php regular expression function_PHP tutorial
PHP regular expression common functions, php regular expression function
1. preg_match()
Function prototype: int preg_match (string $pattern, string $content [, array $matches])
The 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 regular expression matching function 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"; ?>
Typically, using 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.
The functions of eregi_replace() and ereg_replace() are the same, 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 Source code cleaning
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()
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>TEST</H1>My Picture<Img src=”my.gif”></Body></HTML>”; //输出结果中HTML标签将全部为小写字母 echo preg_replace ( "/(<//?)(/w+)([^>]*>)/e", "'//1'.strtolower('//2').'//3'", //此处的模式变量//2将被strtolower转换为小写字符 $html_body); ?>
Tips
The preg_replace function uses Perl-compatible regular expression syntax and is generally a faster alternative to ereg_replace. If you only want to do a simple replacement of a string, you can use the str_replace function.
PHP function preg_match_all code example: php self-study network 2< /div< div id="biuuu_3"php self-study network 3< /div'; PHP function preg_match_all example requirements: take out the ID and content of each DIV element separately, Such as biuuu, biuuu_2, biuuu_3, php self-study network, php self-study network 2 and php self-study network 3 (some common website grabbing methods are matched in this way) Analysis: The string is a simple HTML element, and each DIV element corresponds to this one ID and content are independent. First consider how to extract the ID value and content within a DIV, such as: php self-study network, and then match other similar elements. Two values need to be taken out from a DIV, that is, two matching expressions. The first expression is used to match the ID value (biuuu), and the second expression is used to match the content of the ID (php self-study network). Regular Commonly used expressions use parentheses, then the previous element will become the following form: < div id="(biuuu)"(php self-study network)< /div < div id="(Expression 1 )"(Expression 2)< /div Expression 1: [a-zA-Z0-9_]+ (indicates matching uppercase and lowercase letters, numbers and underscores) Expression 2: [^<]+ (indicates no match < and characters) In this way, the subexpression that the PHP function preg_match_all needs to match is implemented, but it also needs to match an expression. The method is as follows: Expression: / '"(Expression 1)"'(Expression 2 )/ Note that the double quotes " and / need to be escaped using escape characters, and then put the first two expressions in, as follows: '"([a-z0-9_]+)"'/< div id= "([a-z0-9_]+)"([^<]+)< /div/ In this way, a regular expression that matches the ID value and content of each DIV element is implemented, and then the preg_match_all function is used to test as follows: $html = '< div id="biuuu"php self-study network< /div< div id="biuuu_2"php self-study network 2< /div< div id="biuuu_3"php self-study network 3< /div'; preg_match_all ('/< divsiddivsid="([a-z0-9_]+)"([^<]+)< /div/',$html,$result); var_dump($result); PHP function preg_match_all Example results: array(3) { [0]= array(3) { [0]= string(30) "php self-study network" [1]= string(33) "php self-study network 2" [2]= string( 33) "php self-study network 3" } [1]= array(3) { [0]= string(5) "biuuu" [1]= string(7) "biuuu_2" [2]= string(7) "biuuu_3& ......The rest of the full text>>
Today we will introduce to you the use of PHP function preg_match_all in regular expression testing. PHP function preg_match_all code example: $html = < div id="biuuu">php self-study network< /div>php self-study network 2< /div>< div id="biuuu_3">php self-study network 3< /div>; PHP dynamic website development skills share the types of PHP printing functions Summarize the details of $_SERVER in PHP Organize the specific usage of the PHP function stristr() Introduce the skills of PHP code performance optimization Explain the PHP function preg_match_all Example requirements: respectively Extract the ID and content of each DIV element, such as biuuu, biuuu_2, biuuu_3, php self-study network, php self-study network 2 and php self-study network 3 (some common website grabbing methods are matched in this way) Analysis: The string is a simple HTML elements, each DIV element corresponds to an ID and content, and is independent. First consider how to extract the ID value and content within a DIV, such as: php self-study network, and then match other similar elements. Two values need to be taken out from a DIV, that is, two matching expressions. The first expression is used to match the ID value (biuuu), and the second expression is used to match the content of the ID (php self-study network). Regular Commonly used expressions use parentheses, then the previous element will become the following form: < div id="(biuuu)">(php self-study network)< /div> < div id="( Expression 1)">(Expression 2)< /div> OK, use the parentheses above to divide the areas that need to be matched. The next step is how to match the content in each expression. We guess that an ID may be Letters, numbers or underscores, then this becomes simple, you can use square brackets, as follows: Expression 1: [a-zA-Z0-9_]+ (means to match uppercase and lowercase letters, numbers and underscores) What about Match expression 2, because the content of the ID can be any character, but it should be noted that the < or > characters cannot be matched, because if these two characters are matched, all DIVs used later will be matched, so these need to be excluded. Elements starting with two characters, that is, do not match the < or > characters, as follows: Expression 2: [^<>]+ (indicates that the < and > characters are not matched) In this way, the PHP function preg_match_all needs The matching subexpression is implemented, but an expression needs to be matched. The method is as follows: Expression: / "(Expression 1)">(Expression 2)/ Note the double quotes "" and / required Use escape characters to escape, and then put the first two expressions in, as follows: "([a-z0-9_]+)">/< div id="([a-z0-9_]+) ">([^<>]+)< /div>/ This implements a regular expression that matches the ID value and content of each DIV element, and then uses the preg_match_all function to test as follows: $html = < div id="biuuu">php self-study network< /div>< div id="biuuu_2">php self-study network 2< /div>< div id="biuuu_3">php self-study network 3< /div> ;; p...The rest of the text>>

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 and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

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.
