PHP Regular Expressions Common functions, PHP Regular expression function _php Tutorial

Source: Internet
Author: User

PHP Regular Expressions 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 the $pattern. If $matches is provided, the matching result is placed in it. $matches [0] will contain text that matches the entire pattern, $matches [1] will contain the first captured content that matches the pattern cell in parentheses, and so on. This function only matches once, and eventually returns the number of matches for 0 or 1. Code 6.1 shows a code example for the Preg_match () function.
Code 6.1 date-time matching
The code is as follows:

<?php//String that needs to be matched. The date function returns $content = "Current date and Time was". Date ("y-m-d h:i a"). ", we are learning PHP together."; The usual method of matching time if (Preg_match ("//d{4}-/d{2}-/d{2}/d{2}:/d{2} [ap]m/", $content, $m)) {echo "matches the time is:". $m [0]. "/n"; }//Because the time pattern is obvious, it can also be easily matched if (Preg_match ("/([/d-]{10}) ([/d:]{5} [Ap]m]/", $content, $m)) {echo "The current date is:". $m [1]. "/n"; echo "Current time is:". $m [2]. "/n"; }?>

This is a simple dynamic text string matching instance. Assuming that the current system time is "August 17, 2006 13:25", the output will be as follows.
The time to match 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 a matching function of the POSIX extended library expression. Eregi () is a case-insensitive version of the Ereg () function. The two functions are similar to Preg_match, but the function returns a Boolean value that indicates whether the match was successful or not. It is necessary to note that the first parameter of the POSIX extension library function accepts a regular expression string, that is, it does not require a delimiter. For example, code 6.2 is a method for file name security checks.
Code 6.2 Security checks for file names
The code is as follows:

<?php $username = $_server[' Remote_user '); $filename = $_get[' file ']; Filter the file name to ensure system security if (!ereg (' ^[^./][^/]*$ ', $userfile)) {die (' This is not an illegal filename! '); }//Filter the user name if (!ereg (' ^[^./][^/]*$ ', $username)) {die (' This is not an invalid user name ')}//through security filtering, flattening the file path $thefile = "/home/$username/$f Ilename ";?>

Typically, using a Perl-compatible regular expression matching function, Perg_match (), will be faster than using Ereg () or eregi (). It is recommended to use the STRSTR () or Strpos () function if you are looking for a substring that contains only one string.

Substitution of regular expressions

1. Ereg_replace () and Eregi_replace ()

Function Prototypes: String ereg_replace (String $pattern, String $replacement, String $string)
String Eregi_replace (String $pattern, String $replacement, String $string)
Ereg_replace () searches the $string for the pattern string $pattern and replaces the matched result with $replacement. When a pattern cell (or sub-mode) is included in a $pattern, the position of the $replacement in the form "/1" or "$" is replaced by the contents of those sub-patterns that are matched in turn. The "/0" or "$ A" refers to the contents of the entire matching string. It is important to note that the backslash is used as an escape character in double quotes, so you must use the form "//0", "//1".
Eregi_replace () and ereg_replace () are functionally consistent, except that the former ignores case. Code 6.6 is an applied example of this function, which demonstrates how to do a simple cleanup of the program source code.
Code 6.6 Cleanup of source code
The code is as follows:

<?php $lines = file (' source.php '); Reads the file into the array for ($i =0; $i
 
  

2. Preg_replace ()

Function prototypes: Mixed preg_replace (mixed $pattern, mixed $replacement, mixed $subject [, int $limit])
Preg_replace is more powerful than ereg_replace. The first three parameters can be used arrays, the fourth parameter $limit can set the number of substitutions, the default is to replace all. Code 6.7 is an application instance of an array substitution.
Code 6.7 Array Substitution
The code is as follows:

<?php//String $string = "Name: {name}
/nemail: {Email}
/naddress: {Address}
/n "; Mode $patterns =array ("/{address}/", "/{name}/", "/{email}/"); Replace string $replacements = Array ("No.5, Wilson St, New York, U.S.A", "Thomas Ching", "tom@emailaddress.com",); Output mode replacement result print preg_replace ($patterns, $replacements, $string);?>

The output results are as follows.

The pattern modifier "E" can be used in preg_replace regular expressions. The effect is to use the match result as an expression, and it can be re-calculated. For example:
The code is as follows:

<?php $html _body = "

TEST

My picture "; The HTML tags in the output will be all lowercase letters echo preg_replace ("/( ]*>)/E", "'//1 '. Strtolower ('//2 ')." 3 ' ",///The mode variable//2 here will be converted to lowercase characters by strtolower $html _body);?>

Tips
The Preg_replace function uses Perl-compatible regular expression syntax, which is often a faster alternative than ereg_replace. If you simply replace the string, you can use the Str_replace function.


How to test the effect of regular expressions using PHP function Preg_match_all

  PHP function Preg_match_all code example: PHP Self-learning Network 2</div< div id= "biuuu_3" PHP self-study network 3</div ';  PHP function Preg_match_all Instance requirements: Separate the ID and content of each div element, such as biuuu,biuuu_2,biuuu_3,php self-study nets, PHP self-learning Nets 2 and PHP self-study Network 3 (some of the commonly used method of grasping the station is such a match) Analysis: string is a simple HTML element, each DIV element pair should be an ID and content, and is independent, first of all, consider how to take out a div inside the ID value and content, such as: PHP Self-learning Network, and then match other similar elements. A DIV needs to take out two values, that is, two matching expressions, the first expression is used to match the ID value (BIUUU), the second expression is used to match the contents of the ID (PHP self-Learning Network), regular expressions commonly used expressions use parentheses, then the preceding elements will be as follows: < Div id= "(biuuu)" (PHP self-study net) </div < div id= "(expression 1)" (expression 2) </div expression 1:[a-za-z0-9_]+ (for matching uppercase and lowercase letters, numbers and underscores) expression 2:[^< ]+ (indicates mismatch <和字符)  这样,php函数preg_match_all需要匹配的子表达式就实现了,但是还要需要匹配一个的表达式,方法如下:  表达式:/ '"(表达式1)"'(表达式2)/  注意其中的双引号"和/需要使用转义字符转义,然后把前面两个表达式放进去,如下:  '"([a-z0-9_]+)"'/< div id="biuuu_3" ([^<]+)< /div/  这样就实现一个匹配每一个div元素id值和内容的正则表达式,然后使用preg_match_all函数测试如下:  $html="'<" php自学网< /div< php自学网2< php自学网3< /div'; preg_match_all('/< divsiddivsid="([a-z0-9_]+)" /div/',$html,$result); var_dump($result);  php函数preg_match_all示例结果:  array(3) { [0]="string(5)" "php自学网" [1]="string(7)" "php自学网2" [2]="string(7)" "php自学网3" } "biuuu" "biuuu_2" "biuuu_3&......余下全文> <和字符)  这样,php函数preg_match_all需要匹配的子表达式就实现了,但是还要需要匹配一个的表达式,方法如下:  表达式:/>< div="" id="biuuu_3"><>< /div/  这样就实现一个匹配每一个div元素id值和内容的正则表达式,然后使用preg_match_all函数测试如下:  $html="'<"><><><>< /div';="">< divsiddivsid="([a-z0-9_]+)" /div/',$html,$result);="" var_dump($result);  php函数preg_match_all示例结果:  array(3)="" {="" [0]="string(5)" "php自学网"="" [1]="string(7)" "php自学网2"="" [2]="string(7)" "php自学网3"="" }="" "biuuu"="" "biuuu_2"="" "biuuu_3&......余下全文="">>

How to test the effect of regular expressions using PHP function Preg_match_all

Today we will introduce the application 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 net 3</div>; PHP Dynamic Web Developer tips for sharing php print function Summary php $_server detailed information on how to use the PHP function Stristr () the specific way to introduce PHP code performance optimization techniques to explain PHP functions Preg_match_ All instance requirements: Separate the ID and content of each div element, such as biuuu,biuuu_2,biuuu_3,php self-learning nets, PHP self-learning Nets 2 and PHP self-study Network 3 (some common methods of grasping the site is such a match) analysis: The string is a simple HTML element, Each div element pair should be an ID and content, and be independent, first consider how to take out a div inside the ID value and content, such as: PHP Self-learning Network, and then match other similar elements. A DIV needs to take out two values, that is, two matching expressions, the first expression is used to match the ID value (BIUUU), the second expression is used to match the contents of the ID (PHP self-Learning Network), regular expressions commonly used expressions use parentheses, then the preceding elements will become the following form:< Div id= "(biuuu)" > (PHP Self-study net) </div> < div id= "(expression 1)" > (expression 2) </div> good, use the parentheses to divide the areas that need to be matched, The next step is how to match the contents of each expression, and we suspect that an ID might be a letter, a number, or an underscore, which is easy, and can be implemented using the brackets, as follows: expression 1:[a-za-z0-9_]+ (means matching uppercase and lowercase letters, numbers, and underscores) how to match the expression 2, Because the content of the ID can be any character, but be aware that it does not match <或> The "or" character, because if the match between the two characters will be used to match the Div, so you need to exclude the beginning of the two characters of the element, that is, do not match the "or" character, as follows: Expression 2:[^<>]+ (means mismatch "and" characters) so, PHP function p The Reg_match_all need to match the subexpression, but also need to match an expression, the method is as follows: expression:/"(expression 1)" > (expression 2)/note the double quotation marks "and/need to use escape character escapes, and then put the previous two expressions in, as follows: "([a-z0-9_]+)" >/< div id= "([a-z0-9_]+)" > ([^<>]+) </div>/This implements a regular expression that matches each DIV element ID value and content, Then use the Preg_match_all function to test as follows: $html = < div id= "biuuu" >php self-study net </div>< div id= "biuuu_2" >php self-study net 2</div >< Div id= "biuuu_3" >php self-study net 3</div>; P...... Remaining full text >>
 
/or/or

http://www.bkjia.com/PHPjc/865250.html www.bkjia.com true http://www.bkjia.com/PHPjc/865250.html techarticle PHP Regular expressions commonly used functions, PHP Regular expression function 1. Preg_match () function prototype: int Preg_match (String $pattern, String $content [, array $matches]) Preg_match () function in ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.