| 特性 | POSIX (ereg 系) | PCRE (preg 系) |
|---|---|---|
| 函數前綴 | ereg, ereg_replace, split... | preg_match, preg_replace, preg_split... |
| 語法標準 | POSIX 1003.2 | Perl 兼容 (PCRE) |
| 定界符 | 不需要 | 需要 (如 /pattern/) |
| 效能 | 較慢 | 較快 (C 庫優化) |
| 功能豐富度 | 基礎 | 強大 (斷言、回溯控制、遞歸...) |
| PHP 狀態 | PHP 5.3 棄用,7.0 移除 | 標準推薦 |
int ereg(string $pattern, string $string, array &$regs = null)
範例:日期格式轉換 YYYY-MM-DD → DD.MM.YYYY
<?php
if (ereg("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs)) {
echo "$regs[3].$regs[2].$regs[1]";
} else {
echo "Invalid date format: $date";
}
?>
string ereg_replace(string $pattern, string $replacement, string $string)
範例:
<?php
$string = "This is a test";
echo str_replace(" is", " was", $string); // 字串替換
echo ereg_replace("( )is", "\\1was", $string); // 保留空格
echo ereg_replace("(( )is)", "\\2was", $string); // 使用第二捕獲組
// 整數替換陷阱
$num = 4;
ereg_replace('four', $num, $string); // 錯誤:把 4 當 ASCII 字符
ereg_replace('four', '4', $string); // 正確:字串 '4'
// URL 轉超連結
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "\\0", $text);
?>
int preg_match(string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0)
範例:
<?php
// 不區分大小寫搜尋 "php"
if (preg_match("/php/i", "PHP is the web scripting language")) {
print "A match was found.";
}
// 單詞邊界 \b:只匹配獨立 "web"
preg_match("/\bweb\b/i", "PHP is the web scripting language"); // 匹配
preg_match("/\bweb\b/i", "PHP is the website scripting language"); // 不匹配
// 從 URL 提取域名
preg_match("/^(http:\/\/)?([^\/]+)/i", "https://www.php.net/index.html", $matches);
$host = $matches[2];
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
echo "domain: {$matches[0]}"; // php.net
?>
mixed preg_replace(mixed $pattern, mixed $replacement, mixed $subject, int $limit = -1, int &$count = null)
進階範例:
<?php
// 逆向引用後接數字:${1}1 表示第1組 + 字面數字1
$string = "April 15, 2003";
$pattern = "/(\w+) (\d+), (\d+)/i";
$replacement = "${1}1,\$3";
echo preg_replace($pattern, $replacement, $string); // April1,2003
// 陣列批量替換 (需 ksort 保證順序)
$string = "The quick brown fox";
$patterns = ["/quick/", "/brown/", "/fox/"];
$replacements = ["slow", "black", "bear"];
ksort($patterns); ksort($replacements);
echo preg_replace($patterns, $replacements, $string); // The slow black bear
// /e 修飾符:替換字串作為 PHP 代碼執行 (PHP 7.0+ 移除,改用 callback)
preg_replace("/(<\/?)(\w+)([^>]*>)/e", "'\\1'.strtoupper('\\2').'\\3'", $html_body); // 標籤大寫
// HTML 轉純文本 (完整版)
$search = [
"''si",
"'<[/!]*?[^<>]*?>'si",
"'([\r\n])[\s]+'",
"'&(quot|#34);'i", "'&(amp|#38);'i", "'&(lt|#60);'i",
"'&(gt|#62);'i", "'&(nbsp|#160);'i", "'(\d+);'"
];
$replace = ["", "", "\\1", "\"", "&", "<", ">", " ", "chr(\\1)"];
$text = preg_replace($search, $replace, $document);
?>
ereg → preg_match,ereg_replace → preg_replacepattern → /pattern/[[:alpha:]] → [a-zA-Z] 或 \p{L}\\1 → $1 (推薦) 或 \\1/e 修飾符,改用 preg_replace_callback