
Mẫu Regular Expressions hữu ích
Không chỉ trong PHP mà ở nhiều ngôn ngữ khác Regular Expressions xuất
hiện một cách thường xuyên, điều này cho thấy sự tiện dụng của nó. Xin giới
thiệu một vài mẫu Regex hữu ích : Tên truy cập Chỉ chấp nhận chữ cái thường,
chữ cái viết hoa, số 0-9, và gạch chân.
view plaincopy to clipboardprint?
1.
$string = "userNaME123456789_";
2.
if (preg_match('/^[a-
z\d_]{023456789}$/i', $string)) { echo "example 1 successful."; }
$string = "userNaME123456789_";
if (preg_match('/^[a-z\d_]{023456789}$/i', $string)) { echo "example 1
successful."; }
Số điện thoại Số điện thoại có dạng : (###)###-####
view plaincopy to clipboardprint?
1.
$string = "(032)555-5555";
2.
if (preg_match('/^(\(?[2-9]{1}[0-9]{2}\)?|[0-9]{3,3}[-. ]?)[ ][0-9]{3,3}[-
. ]?[0-9]{4,4}$/', $string)) {

3.
echo "example 2 successful.";
4.
}
$string = "(032)555-5555";
if (preg_match('/^(\(?[2-9]{1}[0-9]{2}\)?|[0-9]{3,3}[-. ]?)[ ][0-9]{3,3}[-. ]?[0-
9]{4,4}$/', $string)) {
echo "example 2 successful.";
}
Địa chỉ Email dạng ho.ten@domain.com.vn
view plaincopy to clipboardprint?
1.
$string = "first.last@domain.com.vn";
2.
if (preg_match( '/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-
Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/', $string)) {
3.
echo "example 3 successful.";
4.
}
$string = "first.last@domain.com.vn";

if (preg_match( '/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-
9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/', $string)) {
echo "example 3 successful.";
}
Mã Postal :
view plaincopy to clipboardprint?
1.
$string = "55324-4324";
2.
if (preg_match('/^[0-9]{5,5}([- ]?[0-9]{4,4})?$/', $string)) {
3.
echo "example 4 successful.";
4.
}
$string = "55324-4324";
if (preg_match('/^[0-9]{5,5}([- ]?[0-9]{4,4})?$/', $string)) {
echo "example 4 successful.";
}
Địa chỉ ip :

view plaincopy to clipboardprint?
1.
$string = "255.255.255.0";
2.
if (preg_match( '^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-
4]\d|1\d\d|[1-9]\d|\d)){3}$', $string)) {
3.
echo "example 5 successful.";
4.
}
$string = "255.255.255.0";
if (preg_match( '^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-
4]\d|1\d\d|[1-9]\d|\d)){3}$', $string)) {
echo "example 5 successful.";
}
Mã màu hexadecimal Dạng :#333333, #333. :
view plaincopy to clipboardprint?
1.
$string = "#666666";
2.
if (preg_match('/^#(?:(?:[a-f\d]{3}){1,2})$/i', $string)) {
3.
echo "example 6 successful.";

4.
}
$string = "#666666";
if (preg_match('/^#(?:(?:[a-f\d]{3}){1,2})$/i', $string)) {
echo "example 6 successful.";
}
Comment nhiều dòng Comment dạng : /* * text here */ Thường dùng trong
php, css... :
view plaincopy to clipboardprint?
1.
$string = "/* commmmment */"; if (preg_match('/^[(/*)+.+(*/)]$/', $strin
g)) {
2.
echo "example 7 successful.";
3.
}
$string = "/* commmmment */"; if (preg_match('/^[(/*)+.+(*/)]$/', $string)) {
echo "example 7 successful.";
}

