1. Regular expression is a tool for string search and matching
2. Commonly used regular expression functions in php
3. Function description
$pattern = regular expression
$subject = matching objective function
(1) preg_match() and preg_match_all(): return the number of times the result was matched
eg:
$pattern='/[0-9]/';
$subject = 'weuyr3ui76as83s0ck9';
$m1 = $m2 = array();
t1 = grep_match($pattern, $subject, $m1);
t2 = grep_match_all($pattern, $subject, $m2);
Result: m1 = array([0]=>3)
m2 = array([0]=>array([0]=>3,[1]=>7,[2]=>6,[3]=>8,[4] =>3,[5]=>0,[6]=>9))
t1 = 1
t2 = 7
(2) preg_replace and preg_filter: support array replacement
eg one:
$pattern='/[0-9]/';
$subject = 'weuyr3ui76as83s0ck9';
$replacement = 'ying';
$str1 = preg_replace($pattern, $replacement, $subject);
$str2 = preg_filter($pattern, $replacement, $subject);
Result:
$str1 = 'weuyryinguiyingyingasyingyingsyingckying'
$str2 = 'weuyryinguiyingyingasyingyingsyingckying'
eg two:
$pattern = array('/[0123]/', '/[456]/', '/[789]/')
$replacement = array('Ah', 'La', '妦')
Result:
$str1 = 'weuyrah ui 妦拉as妦ah sah ck 妦'
$str2 = 'weuyrahui妦拉as妦ahsahck妦'
eg three:
$subject = array('weuy', 'r3ui', '76as83', 's', '0ck9');
Result:
$str1 = array([0]=>weuy, [1]=>rui, [2]=>妦拉as妦Ah, [3]=>s, [4]= >Ah ck 妦)
$str2 = array([1]=>rui, [2]=>妦拉as妦妦ah, [4]=>ahck妦)
(3) grep_grep($pattern, array $input): A emasculated version of grep_filter(), only matching, no replacement
eg:
$pattern='/[0-9]/';
$subject = array('weuy', 'r3ui', '76as83', 's', '0ck9');
$arr = preg_grep($pattern, $subject);
Result:
$arr = array([1]=>r3ui, [2]=>76as83, [4]=>0ck9)
(4) grep_split($pattern, $subject): explode is a subset of this function
eg:
$pattern = '/[0-9]/';
$subject = 'You 2 are so good at 3!'
$arr = preg_split($pattern, $subject);
Result:
$arr = ([0]=>You, [1]=>Okay, [2]=>Ah!)