PHP supports two regular expressions: POSIX-style Regular Expressions and Perl-Compatible Regular Expressions.
PHP supports two regular expressions: POSIX-style Regular Expressions and Perl-Compatible Regular Expressions.
The regular expressions that we all call are basically Perl-Compatible Regular Expressions. POSIX regular expressions are basically not used. Therefore, it is not recommended to use them since PHP5.3. Related functions may be deleted in the next PHP version.
As regular expressions are too complex, I want to read a regular expression book later, so I will only introduce some functions compatible with Perl-style regular expressions.
1. delimiters
The delimiters indicate the start and end of a regular expression, which is generally expressed by a slash. In PHP (not tested in other languages at the moment), it can also be replaced by other non-alphanumeric characters. For example,/\ d +/and # \ d + # indicate the same regular expression \ d +. You can also use parentheses, braces, and braces as delimiters, such as [\ d +].
2. Functions
Matching functions: preg_match (); and preg_match_all ();
Replacement function: preg_replace ();
Split function: preg_split ();
Filter Function: preg_grep ();
Sample Code:
The Code is as follows:
$ A = <TEXT
Aaaaaaa 15
Bbbbbbb 16
TEXT;
$ Ret = preg_match (/(\ w +) (\ d +)/, $ a, $ match );
// $ Ret: 1
// $ Match: array (aaaaaaa 15', aaaaaaa, 15 ′)
$ Ret = preg_match_all (/(\ w +) (\ d +)/, $ a, $ match );
// $ Ret: 2
// $ Match: array (
// Array (aaaaaaa 15', bbbbbbbbb 16 ′),
// Array (bbbbbbb, bbbbbbb ),
// Array (15', 16 ′),
//)
$ Ret = preg_match_all (/(\ w +) (\ d +)/, $ a, $ match, PREG_SET_ORDER );
// $ Ret: 2
// $ Match: array (
// Array (aaaaaaa 15', bbbbbbbbb, 15 ′),
// Array (bbbbbbb 16', bbbbbbb, 16 ′),
//)
$ B = preg_replace (/(\ w +) (\ d +)/, \ 1, \ 2', $ );
// $ B: aaaaaaa, 15
// Bbbbbbb, 16 ′
$ C = preg_split (/\ s/, $ );
// $ C: array (aaaaaaa, 15', bbbbbbb, 16 ′)
$ Files = array(aa.txt, bb.xls, cc.txt );
$ TxtFiles = preg_grep (/. * \. txt/, $ files );
// $ TxtFiles: array(aa.txt, cc.txt)
References:
PHP programming, 2003, chapter 4 string, Regular Expression