PHP Regular Expression


In string match, one Regular Expression pattern can usually match multiple strings which is sometimes very useful. Regular Expression functions include preg_match(), preg_replace(), preg_split() etc.

<?PHP
	$arr = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
	foreach($arr as $dy)
	{
	   if (preg_match("/t.?u/i",$dy))
	   echo "$dy\n";
	}
	Tuesday
	Thursday
	Saturday 
?>

Regular Expression Syntax:
SyntaxDescription
\dDigit, 0,1,2 ... 9
\DNot Digit
\sSpace
\SNot Space
\wWord
\WNot Word
\tTab
\nNew line
^Beginning of the string
$End of the string
\Escape special characters, e.g. \\ is "\", \+ is "+"
|Alternation match. e.g. /(e|d)n/ matches "en" and "dn"
Any character, except \n or line terminator
[ab]a or b
[^ab]Any character except a and b
[0-9]All Digit
[A-Z]All uppercase A to Z letters
[a-z]All lowercase a to z letters
[A-z]All Uppercase and lowercase a to z letters
i+i at least one time
i*i zero or more times
i?i zero or 1 time
i{n}i occurs n times in sequence
i{n1,n2}i occurs n1 - n2 times in sequence
i{n,}i occures >= n times
\0NUL
\fForm feed character
\rCarriage return character
\vVertical tab
\xhhhhUnicode with 4 characters of hexadecimal code hhhh
\xhhCharacter with 2 characters of hexadecimal code hh
?=iLookahead matches only if i is followed
?!iLookahead matches only if i is not followed