Regular expressions for PHP learning. The regular expressions that we all call are basically Perl-compatible regular expressions. POSIX-style regular expressions are basically not used, so since PHP5.3, we have not pushed the regular expressions that we all call to basically refer to regular expressions compatible with Perl-style 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
Bytes. POSIX-style regular expressions are basically not used, so it has not been pushed since PHP5.3...