There are two ways to declare a regular expression in PHP, one of which is POSIX legacy mode, which is not commonly used. There is also a common pcre method in other languages.
1. The matching method of the regular expression and returns the matching entry: array preg_grep (string Reg,array is matched by the arrays);
$reg= "/a|b/"; $str=array(' abcabc ', ' BCD ', ' KKK '); $ar=preg_grep($reg,$str); Print_r ($ar); // Array ([0] = ABCABC [1] = BCD)
2. Determine if the target string matches the regular expression: int Preg_match (string regular expression, string target string, array (optional)); int Preg_match_all (string regular expression, string target string, array holds arrays);
$arr=$arr 2=Array(); $reg= "/a|b/"; $str= ' CCCACCCCCAA '; Echo Preg_match_all($reg,$str,$arr);//3 Echo Preg_match($reg,$str,$arr 2);//1 Print_r($arr);//Array ([0] = = Array ([0] = a [1] = = a [2] + a)) Print_r($arr 2);//Array ([0] = a)
3. Escapes the special character in the string Preg_quote string (string target string, string specifies the escaped string (optional));
$str= "\$$^&#@"; $str 2= ' \$$^&#@ '; Echo Preg_quote ($str); // \$\$\^&#@ Echo Preg_quote ($str 2); // \\\$\$\^&#@ Echo Preg_quote ($str, ' @ '); // \$\^&#\@
4. Replacement function for regular expressions: Preg_replace (string literal, string substitution character, string target string, int substitution number (optional, default replace All));
$reg= "/a|b/"; $str= ' ABCSKDFAASDCA '; Echo Preg_replace ($reg, ' @ ',$str); // @@[email Protected]@[email protected] Echo Preg_replace ($reg, ' @ ',$str, 2); // @ @cskdfaasdca
5. Replacement function for regular expressions: Preg_replace_callback (string literal, string callback function name, string target string, int optional substitution number);
functionCall$ss){ $ss= ' obj '; return $ss; }$reg= "/a|b/";$str= ' ABCDEFGA ';Echo Preg_replace_callback($reg, ' call ',$str);//ObjobjcdefgobjEcho Preg_replace($reg, ' call ',$str, 2);//OBJOBJCDEFGA
6. Split the string with a regular expression, returning an array: array preg_split (string literal, string target string, int split number (optional)); Note: the match is deleted as a split.
$reg= "/a/"; $str= ' abcadeafga '; Print_r (preg_split($reg,$str)); // Array ([0] = [1] [+] = BC [2] = + de [3] = FG [4] = =) Print_r (preg_split($reg,$str, 2)); // Array ([0] = [1] = BCADEAFGA)