Regular Expression - 正規表現
Regular Expression(RE) - 正規表現 (せいきひょうげん)
1. Định nghĩa:
RE là một phươg pháp định nghĩa ra các mẫu(pattern) và thực hiện tìm kiếm, tính toán theo các mẫu đó.
Trong PHP bạn có thể dùng RE để tìm kiếm một đoạn text theo một mẫu. Bạn có thể sửa hoặc thay đổi kết quả trả về.
Ví dụ:
Đoạn mã sau chuyển từ [địa chỉ email dạng text] sang dạng [mailto:điạ chỉ email dạng link]
$html = preg_replace(’/[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}/i’,
‘$0‘, $text);
2. Một số ký hiệu cơ bản
- / /:Bắt đầu và kết thúc một pattern: /$pattern/
- /./: dấu . đại diện cho 1 ký tự (/.at/ sẽ trả lại là bat, cat, rat)
- /*/: dấu * đại diện cho nhiều ký tự(/*at/ sẽ trả lại là bat, thebat, sprat)
- /+/: dấu + đại diện cho nhiều ký tự(/.+at/ sẽ trả lại là brat, sprat nhưng khôn trả lại at)
- /?/: dấu ? để hỏi xem có matches hay không
- /[]/: bên trong nó biểu hiện thứ tự (/[a-z]/ từ a đến z)
- /^/: bắt đầu (/^a/ bắt đầu là chữ a)
- /$/: kết thúc (’/^[aeiou]+$/ nghĩa là chỉ lấy ra đoạn aeio)
- /|/: ký hiệu hoặc (’/(gif|jpeg)/ nghĩa là tìm ảnh có kiểu gif hoặc jpeg)
-/\w/: lấy chữ [a-zA-Z0-9_]
-/\d/: lấy số [0-9]
-/\s/: lấy whitespace
-/\b/: lấy một từ đứng ngay trước \b
-/i/: không quan tâm chữ hoa hay chữ thường, lấy tất

Matching Words
/S+/ // everything that isn’t whitespace
/[A-Z’-]+/i // all upper and lowercase letters, apostrophes, and hyphens
Comment by hungnv — January 5, 2007 @ 5:04 am
Matching a Valid Email Address
/^[^@s]+@([-a-z0-9]+.)+[a-z]{2,}$/i
Comment by hungnv — January 5, 2007 @ 5:05 am
/
^ # anchor at the beginning
[^@s]+ # name is all characters except @ and whitespace
@ # the @ divides name and domain
(
[-a-z0-9]+ # (sub)domains are letters, numbers, and hyphens
. # separated by a period
)+ # and we can have one or more of them
(
[a-z]{2} # TLDs can be a two-letter alphabetical country code
|com|net # or one of
|edu|org # many
|gov|mil # possible
|int|biz # three-letter
|pro # combinations
|info|arpa # or even
|aero|coop # a few
|name # four-letter ones
|museum # plus one that’s six-letters long!
)
$ # anchor at the end
/ix # and everything is case-insensitive
Comment by hungnv — January 5, 2007 @ 5:08 am
Finding All Lines in a File That Match a Pattern
$pattern = “/bo’reillyb/i”; // only O’Reilly books
$ora_books = preg_grep($pattern,file(’/path/to/your/file.txt’));
Comment by hungnv — January 5, 2007 @ 6:52 am
Capturing Text Inside HTML Tags
$html =PHP Cookbook
Other Chapters
Regular Expressions
Other Recipes
Capturing Text Inside of HTML Tags
Problem
Solution
Discussion
See Also
_END_;
preg_match_all(’#(.+?) #is’, $html, $matches);
for ($i = 0, $j = count($matches[0]); $i < $j; $i++) {
print str_repeat(’ ‘, 2 * ($matches[1][$i] - 1)) . $matches[2][$i] . “n”;
}
You get:
PHP Cookbook
Regular Expressions
Capturing Text Inside of HTML Tags
Problem
Solution
Discussion
See Also
Comment by hungnv — January 5, 2007 @ 7:17 am