TopDev

Các hàm biểu thức chính quy - PHP RegEx

minhu 📖 3 phút đọc

PHP cung cấp các hàm mạnh mẽ để làm việc với biểu thức chính quy (Regular Expressions), bao gồm hai phần mở rộng chính: PCRE (Perl Compatible Regular Expressions)POSIX. Tuy nhiên, PCRE được sử dụng rộng rãi hơn và được khuyến nghị sử dụng. Dưới đây là một số hàm chính của PCRE cùng với các ví dụ minh họa.

Các hàm chính của PCRE#

  • preg_match(): Tìm kiếm một lần khớp trong chuỗi.

` $pattern = "/\bword\b/"; $string = "This is a word in a sentence.";

if (preg_match($pattern, $string, $matches)) { echo "Match found: " . $matches[0]; // Match found: word } else { echo "No match found."; } `

  • preg_match_all(): Tìm kiếm tất cả các lần khớp trong chuỗi.

` $pattern = "/\bword\b/"; $string = "This word is a word in a sentence with the word repeated.";

if (preg_match_all($pattern, $string, $matches)) { echo "Matches found: " . count($matches[0]); // Matches found: 3 } else { echo "No matches found."; } `

  • preg_replace(): Thay thế các lần khớp trong chuỗi bằng một chuỗi khác.

` $pattern = "/\bword\b/"; $replacement = "phrase"; $string = "This word is a word in a sentence with the word repeated.";

$newString = preg_replace($pattern, $replacement, $string); echo $newString; // This phrase is a phrase in a sentence with the phrase repeated. `

  • preg_split(): Chia chuỗi thành mảng bằng biểu thức chính quy.

` $pattern = "/[\s,]+/"; $string = "This,is a test,string";

$parts = preg_split($pattern, $string); print_r($parts); // Array ( [0] => This [1] => is [2] => a [3] => test [4] => string ) `

  • preg_grep(): Trả về các phần tử của một mảng khớp với biểu thức chính quy.

` $pattern = "/^test/"; $array = ["test1", "example", "test2", "sample"];

$result = preg_grep($pattern, $array); print_r($result); // Array ( [0] => test1 [2] => test2 ) `

Các hàm kiểm tra biểu thức chính quy#

  • preg_quote(): Trích dẫn các ký tự đặc biệt trong biểu thức chính quy.

` $pattern = "/". preg_quote("example.com") . "/"; $string = "Visit example.com for more info.";

if (preg_match($pattern, $string, $matches)) { echo "Match found: " . $matches[0]; // Match found: example.com } else { echo "No match found."; } `

  • preg_last_error(): Trả về mã lỗi của lần sử dụng biểu thức chính quy cuối cùng.

` $pattern = "/\bword\b/"; $string = "This is a word in a sentence.";

preg_match($pattern, $string);

if (preg_last_error() === PREG_NO_ERROR) { echo "No errors."; } else { echo "There was an error."; } `

Ví dụ thực tế#

Tìm và thay thế trong văn bản

` $pattern = "/\b(https?://[^\s]+)/"; $string = "Visit https://example.com or http://example.org for more info.";

$replacement = '$1'; $newString = preg_replace($pattern, $replacement, $string);

echo $newString; // Visit https://example.com or http://example.org for more info. `

Kiểm tra định dạng email

` $email = "user@example.com"; $pattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/";

if (preg_match($pattern, $email)) { echo "Valid email."; } else { echo "Invalid email."; } `

Tách tên và họ từ chuỗi

` $string = "John Doe"; $pattern = "/(\w+)\s+(\w+)/";

if (preg_match($pattern, $string, $matches)) { echo "First name: " . $matches[1] . "\n"; // First name: John echo "Last name: " . $matches[2] . "\n"; // Last name: Doe } `

Các tùy chọn bổ sung#

  • i: Không phân biệt chữ hoa chữ thường.

` $pattern = "/word/i"; $string = "This is a Word in a sentence.";

if (preg_match($pattern, $string)) { echo "Match found."; } else { echo "No match found."; } `

  • m: Đa dòng, ^$ khớp với đầu và cuối của mỗi dòng.

` $pattern = "/^word/m"; $string = "word on first line\nword on second line";

if (preg_match_all($pattern, $string, $matches)) { echo "Matches found: " . count($matches[0]); // Matches found: 2 } `

  • s: Chế độ đơn dòng, . khớp với mọi ký tự bao gồm cả ký tự xuống dòng.

` $pattern = "/word.*end/s"; $string = "word starts\nand ends";

if (preg_match($pattern, $string)) { echo "Match found."; } else { echo "No match found."; } `

Những hàm này giúp bạn xử lý và thao tác với chuỗi bằng biểu thức chính quy trong PHP một cách hiệu quả.

Bài liên quan trong #PHP

✓ Đã sao chép link