8 mẫu Regular Expressions 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.

$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 : (###)###-####

$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

$string = "first.last@domain.co.uk";
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

$string = "55324-4324";
if (preg_match('/^[0-9]{5,5}([- ]?[0-9]{4,4})?$/', $string)) {
echo "example 4 successful.";
}

Địa chỉ ip

$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.

$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…

$string = "/* commmmment */";
if (preg_match('/^[(/*)+.+(*/)]$/', $string)) {
echo "example 7 successful.";
}

Ngày
Ngày dạng MM/DD/YYYY

$string = "10/15/2007";
if (preg_match('/^\d{1,2}\/\d{1,2}\/\d{4}$/', $string)) {
echo "example 8 successful.";
}

(Sưu tầm)

Popularity: 14% [?]


  1. No comments yet.

  1. No trackbacks yet.

Chọn kiểu gõ: Tự động TELEX VNI Tắt

Bad Behavior has blocked 47 access attempts in the last 7 days.