Regular expressions for PHP learning
- 2020-03-31 21:37:07
- OfStack
What we now mean by regular expressions is basically perl-compliant regular expressions. Posix-style regular expressions are largely unused, so they have not been recommended since PHP5.3, and the next version of PHP will probably remove them.
On regular expressions, I want to focus on a book on regular expressions because they are too complex, so I'll just cover some functions that are compatible with perl-style regular expressions.
1. The delimiter
Delimiters represent the beginning and end of a regular expression, usually expressed as slashes (/). In PHP (which is not yet tested in other languages), it can also be replaced with other non-alphanumeric characters. Such as /\d+/ and #\d+# represent the same regular expression \d+. You can also use pairs of braces, brackets, and braces as delimiters, such as [\d+].
2. The function
Match function: preg_match(); And preg_match_all ();
Preg_replace ();
Split function: preg_split();
Filter function: preg_grep();
Sample code:
Reference:
PHP programming, 2003, chapter 4 strings, regular expressions
On regular expressions, I want to focus on a book on regular expressions because they are too complex, so I'll just cover some functions that are compatible with perl-style regular expressions.
1. The delimiter
Delimiters represent the beginning and end of a regular expression, usually expressed as slashes (/). In PHP (which is not yet tested in other languages), it can also be replaced with other non-alphanumeric characters. Such as /\d+/ and #\d+# represent the same regular expression \d+. You can also use pairs of braces, brackets, and braces as delimiters, such as [\d+].
2. The function
Match function: preg_match(); And preg_match_all ();
Preg_replace ();
Split function: preg_split();
Filter function: preg_grep();
Sample code:
$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 ' , bbbbbbb 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 ' , bbbbbbb, 15 ' ),
// array(bbbbbbb 16 ' , bbbbbbb, 16 ' ),
// )
$b = preg_replace(/(w+) (d+)/, 1, 2 ' , $a);
// $b : aaaaaaa, 15
// bbbbbbb, 16 '
$c = preg_split(/s/, $a);
// $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)
Reference:
PHP programming, 2003, chapter 4 strings, regular expressions