1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
| <?php
echo "【1. 零宽断言(前瞻/后顾)】\n";
$password_pattern = '/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?<!^\d).{8,}$/';
$passwords = [ "ValidPass123", "invalidpass123", "VALIDPASS123", "ValidPassword", "1InvalidPass", "Sh0rt", "Valid1Pass" ];
foreach ($passwords as $pwd) { $result = preg_match($password_pattern, $pwd); echo sprintf("[%-12s] %s\n", $pwd, $result ? "✓ 强密码" : "✗ 弱密码 - 不符合复杂度要求" ); }
echo "\n【2. 命名捕获组】\n";
$date_pattern = '/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})|(?P<day2>\d{2})\/(?P<month2>\d{2})\/(?P<year2>\d{4})/';
$dates = [ "2023-12-25", "31/12/2023", "12-25-2023" ];
foreach ($dates as $date) { if (preg_match($date_pattern, $date, $matches)) { if (!empty($matches['year'])) { $year = $matches['year']; $month = $matches['month']; $day = $matches['day']; } else { $year = $matches['year2']; $month = $matches['month2']; $day = $matches['day2']; } echo "[$date] ✓ 有效日期: {$year}年{$month}月{$day}日\n"; } else { echo "[$date] ✗ 无效日期格式\n"; } }
echo "\n【3. 模式修饰符详解】\n";
$text_multiline = "苹果\nBanana\n樱桃\nDate"; $pattern_multiline = '/^[\p{L}]{3,}$/mu';
echo "多行文本:\n$text_multiline\n"; preg_match_all($pattern_multiline, $text_multiline, $matches_multiline); echo "匹配结果(多行+Unicode): " . implode(", ", $matches_multiline[0]) . "\n";
$pattern_verbose = ' / # 分隔符 \b # 单词边界 (?<word> # 命名捕获组 \w+ # 一个或多个单词字符 ) \s+ # 一个或多个空白字符 \k<word> # 重复前面捕获的相同单词 \b # 单词边界 /x # 扩展模式 ';
$text_repeat = "the the quick brown fox fox jumps over the lazy dog dog"; if (preg_match_all($pattern_verbose, $text_repeat, $matches_repeat)) { echo "重复单词检测: " . implode(", ", $matches_repeat[0]) . "\n"; }
echo "\n【4. Unicode属性支持】\n";
$international_text = "Hello 你好 123 こんにちは 456"; $pattern_unicode = '/[\p{L}\p{N}]+/u';
preg_match_all($pattern_unicode, $international_text, $matches_unicode); echo "原始文本: $international_text\n"; echo "Unicode匹配结果: " . implode(", ", $matches_unicode[0]) . "\n";
echo "\n【5. 回溯控制】\n";
$dangerous_pattern = '/^(a+)+$/'; $safe_pattern = '/^(?>a+)+$/';
$test_string = str_repeat('a', 25) . 'b';
$start = microtime(true); $result_dangerous = @preg_match($dangerous_pattern, $test_string, $matches, 0, 1000000); $time_dangerous = microtime(true) - $start;
$start = microtime(true); $result_safe = preg_match($safe_pattern, $test_string); $time_safe = microtime(true) - $start;
echo "回溯控制测试:\n"; echo "危险模式执行时间: " . sprintf('%.6f', $time_dangerous) . "s, 结果: " . ($result_dangerous === false ? "超时/错误" : $result_dangerous) . "\n"; echo "安全模式执行时间: " . sprintf('%.6f', $time_safe) . "s, 结果: $result_safe\n";
echo "\n【6. 高级URL解析】\n";
$url_parser = '/ ^ # 字符串开始 (?: (?<scheme>[a-z]+) # 协议(命名捕获) :\/\/ # :// )? # 协议部分是可选的 (?: (?<auth>[^@]+)@ # 认证信息 username:password@ )? # 认证信息是可选的 (?<host> # 主机名(命名捕获) (?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+ # 子域名 [a-z]{2,63} # 顶级域名 | # 或者 \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} # IPv4地址 ) (?::(?<port>\d+))? # 端口(命名捕获,可选) (?<path>\/[^\?]*)? # 路径(命名捕获,可选) (?:\?(?<query>[^#]*))? # 查询参数(命名捕获,可选) (?:#(?<fragment>.*))? # 片段(命名捕获,可选) $ # 字符串结束 /ix';
$urls = [ "https://user:pass@example.com:8080/path/to/file?query=1#fragment", "http://sub.domain.co.uk", "ftp://192.168.1.1/file.txt", "example.com/path", "invalid_url" ];
foreach ($urls as $url) { echo "\n分析URL: $url\n"; if (preg_match($url_parser, $url, $matches)) { $result = []; foreach ($matches as $key => $value) { if (!is_int($key) && $value !== '') { $result[$key] = $value; } } echo "✓ 有效URL\n"; foreach ($result as $name => $value) { echo " $name: $value\n"; } } else { echo "✗ 无效URL格式\n"; } }
echo "\n【7. 增强版正则表达式工具类】\n";
class AdvancedRegexHelper { const EMAIL_PATTERN = '/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i'; const URL_PATTERN = '/^(?:https?:\/\/)?(?:[a-z0-9-]+\.)+[a-z]{2,6}(?:\/[\w\-\.?%&=]*)?$/i'; const PHONE_PATTERN = '/^\+?1?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})$/'; const CREDIT_CARD_PATTERN = '/^(?<visa>4\d{12}(?:\d{3})?)|(?<mastercard>5[1-5]\d{14})|(?<amex>3[47]\d{13})$/'; const HTML_TAG_PATTERN = '/<([a-z]+)([^<]*)>(.*?)<\/\1>/is'; public static function validateEmail($email) { return self::safeRegexMatch(self::EMAIL_PATTERN, $email); } public static function validateUrl($url) { return self::safeRegexMatch(self::URL_PATTERN, $url); } public static function validatePhone($phone) { return self::safeRegexMatch(self::PHONE_PATTERN, $phone); } public static function validateCreditCard($cardNumber) { $cleanCard = preg_replace('/\s+/', '', $cardNumber); return self::safeRegexMatch(self::CREDIT_CARD_PATTERN, $cleanCard); } public static function extractEmails($text) { return self::safeRegexMatchAll(self::EMAIL_PATTERN, $text); } public static function extractUrls($text) { return self::safeRegexMatchAll(self::URL_PATTERN, $text); } public static function extractPhoneNumbers($text) { return self::safeRegexMatchAll(self::PHONE_PATTERN, $text); } public static function maskCreditCard($cardNumber) { $cleanCard = preg_replace('/\D/', '', $cardNumber); if (!self::validateCreditCard($cleanCard)) { return "无效的信用卡号"; } $last4 = substr($cleanCard, -4); $masked = str_repeat('*', strlen($cleanCard) - 4) . $last4; return preg_replace('/(\*{4})(?=\*{4})/', '$1 ', $masked); } public static function sanitizeHtml($html) { $allowedTags = ['b', 'i', 'u', 'em', 'strong', 'p', 'br', 'a']; return preg_replace_callback( self::HTML_TAG_PATTERN, function($matches) use ($allowedTags) { $tag = strtolower($matches[1]); if (in_array($tag, $allowedTags)) { if ($tag === 'a') { $href = preg_match('/href\s*=\s*"([^"]*)"/i', $matches[2], $hrefMatches) ? $hrefMatches[1] : ''; if (preg_match('/^(https?:\/\/|mailto:)/i', $href)) { return "<a href=\"$href\">" . self::sanitizeHtml($matches[3]) . "</a>"; } } return "<$tag>" . self::sanitizeHtml($matches[3]) . "</$tag>"; } return self::sanitizeHtml($matches[3]); }, $html ); } public static function makeClickableLinks($text) { $pattern = '/(?<![\w\/])(https?:\/\/|www\.)([\w\-\.]+\.[a-zA-Z]{2,}(?:\/[\w\.\/\?\&\=\-]*)?)/i'; return preg_replace_callback($pattern, function($matches) { $url = $matches[0]; $display = (strlen($url) > 30) ? substr($url, 0, 27) . '...' : $url; if (strpos($url, 'www.') === 0) { $url = 'http://' . $url; } return "<a href=\"$url\" target=\"_blank\">$display</a>"; }, $text); } private static function safeRegexMatch($pattern, $subject, $flags = 0) { set_error_handler(function() {}); $result = preg_match($pattern, $subject, $matches, $flags); restore_error_handler(); if ($result === false) { $error = preg_last_error(); $errorMsg = self::getPregError($error); trigger_error("正则表达式错误: $errorMsg", E_USER_WARNING); return false; } return $result === 1; } private static function safeRegexMatchAll($pattern, $subject, $flags = PREG_PATTERN_ORDER) { set_error_handler(function() {}); $result = preg_match_all($pattern, $subject, $matches, $flags); restore_error_handler(); if ($result === false) { $error = preg_last_error(); $errorMsg = self::getPregError($error); trigger_error("正则表达式错误: $errorMsg", E_USER_WARNING); return []; } return $matches[0] ?? []; } private static function getPregError($code) { switch ($code) { case PREG_NO_ERROR: return "无错误"; case PREG_INTERNAL_ERROR: return "内部错误"; case PREG_BACKTRACK_LIMIT_ERROR: return "回溯限制超出"; case PREG_RECURSION_LIMIT_ERROR: return "递归限制超出"; case PREG_BAD_UTF8_ERROR: return "无效的UTF-8数据"; case PREG_BAD_UTF8_OFFSET_ERROR: return "无效的UTF-8偏移量"; default: return "未知错误 ($code)"; } } }
echo "\n【8. 综合应用:智能文本内容分析器】\n";
class ContentAnalyzer { private $text; private $analysis; public function __construct($text) { $this->text = $text; $this->analysis = []; } public function analyze() { $this->analyzeSentences(); $this->analyzeKeywords(); $this->detectEntities(); $this->identifySensitiveContent(); return $this->analysis; } private function analyzeSentences() { $sentencePattern = '/ (?<= # 后顾断言 [.!?] # 句号、问号、感叹号 [\]\])\'"]* # 可能跟随引号或括号 \s+ # 后跟空白 ) (?=[A-Z]) # 前瞻断言: 下一个字符是大写字母 | # 或者 (?<= # 处理缩写 \b(?:Mr|Mrs|Dr|Prof|Inc|Ltd|Jr|Sr|vs)\. \s+ ) (?=[A-Z])/x'; $sentences = preg_split($sentencePattern, $this->text, -1, PREG_SPLIT_NO_EMPTY); $this->analysis['sentences'] = $sentences; $this->analysis['sentence_count'] = count($sentences); } private function analyzeKeywords() { $wordPattern = '/\b(?!(?:the|and|or|in|on|at|to|for|with|a|an|of|is|are|was|were|be|been|being)\b)[a-zA-Z]{3,}\b/'; preg_match_all($wordPattern, strtolower($this->text), $matches); $words = array_count_values($matches[0]); arsort($words); $this->analysis['top_keywords'] = array_slice($words, 0, 5, true); } private function detectEntities() { $this->analysis['urls'] = AdvancedRegexHelper::extractUrls($this->text); $this->analysis['emails'] = AdvancedRegexHelper::extractEmails($this->text); $this->analysis['phones'] = AdvancedRegexHelper::extractPhoneNumbers($this->text); } private function identifySensitiveContent() { $patterns = [ 'credit_cards' => '/\b(?:\d[ -]*?){13,16}\b/', 'ssn' => '/\b\d{3}[- ]?\d{2}[- ]?\d{4}\b/', 'password_like' => '/\b(password|pass|pwd)\s*[:=]\s*[\'"]?[\w@#$%^&*!]{5,}[\'"]?\b/i' ]; foreach ($patterns as $type => $pattern) { preg_match_all($pattern, $this->text, $matches); if (!empty($matches[0])) { $this->analysis['sensitive'][$type] = count($matches[0]); } } } public function getReport() { $analysis = $this->analyze(); $report = "===== 内容分析报告 =====\n"; $report .= "句子数量: {$analysis['sentence_count']}\n\n"; $report .= "【关键词频率】\n"; foreach ($analysis['top_keywords'] as $word => $count) { $report .= "- $word: $count 次\n"; } $report .= "\n【检测到的实体】\n"; $report .= "- 链接: " . (empty($analysis['urls']) ? "无" : implode(", ", $analysis['urls'])) . "\n"; $report .= "- 邮箱: " . (empty($analysis['emails']) ? "无" : implode(", ", $analysis['emails'])) . "\n"; $report .= "- 电话: " . (empty($analysis['phones']) ? "无" : implode(", ", $analysis['phones'])) . "\n"; if (!empty($analysis['sensitive'])) { $report .= "\n【警告: 检测到敏感内容】\n"; foreach ($analysis['sensitive'] as $type => $count) { $report .= "- $type: $count 处\n"; } $report .= "请检查内容是否包含不应公开的个人信息!\n"; } return $report; } }
echo "\n【9. 高级工具类应用演示】\n";
$emails = ["user@example.com", "invalid-email@", "name+tag@sub.domain.co.uk"]; foreach ($emails as $email) { echo sprintf("邮箱 '%s': %s\n", $email, AdvancedRegexHelper::validateEmail($email) ? "✓ 有效" : "✗ 无效" ); }
$cards = [ "4111 1111 1111 1111", "5500 0000 0000 0004", "3400 0000 0000 009" ]; foreach ($cards as $card) { echo "信用卡: $card → " . AdvancedRegexHelper::maskCreditCard($card) . "\n"; }
$html_content = '<p>安全内容 <b>加粗</b> 和 <a href="https://example.com" onclick="alert(1)">链接</a></p> <script>alert("XSS攻击")</script> 合法<a href="http://example.com/path">内部链接</a>和<a href="javascript:alert(\'bad\')">危险链接</a>';
echo "\n原始HTML:\n$html_content\n"; echo "\n清理后的HTML:\n" . AdvancedRegexHelper::sanitizeHtml($html_content) . "\n";
echo "\n【10. 综合案例:内容安全分析】\n";
$sample_text = <<<TEXT 这是一份测试文档。其中包含一个有效的URL: https://www.example.com/path?query=1#section1 同时还有测试邮箱: contact@example.com 和 support.team@example.co.uk
请注意,我的信用卡号是 4111 1111 1111 1111,社会保险号 123-45-6789。 密码设置为: password=SecurePass123
联系我: (123) 456-7890 或 987-654-3210 更多信息请访问 www.our-company.com 或联系 admin@company.com TEXT;
$analyzer = new ContentAnalyzer($sample_text); echo $analyzer->getReport();
echo "\n【11. 正则表达式性能优化技巧】\n";
$large_text = str_repeat("Lorem ipsum dolor sit amet, consectetur adipiscing elit. ", 1000); $search_word = "dolor";
$pattern_unoptimized = '/\b' . preg_quote($search_word, '/') . '\b/';
$pattern_optimized = '/\b' . preg_quote($search_word, '/') . '\b/S';
$iterations = 10; $time_unoptimized = 0; $time_optimized = 0;
for ($i = 0; $i < $iterations; $i++) { $start = microtime(true); preg_match_all($pattern_unoptimized, $large_text, $matches); $time_unoptimized += microtime(true) - $start; $start = microtime(true); preg_match_all($pattern_optimized, $large_text, $matches); $time_optimized += microtime(true) - $start; }
echo "性能测试 (平均时间):\n"; echo "非优化模式: " . sprintf('%.6f', $time_unoptimized / $iterations) . " 秒\n"; echo "优化模式(S修饰符): " . sprintf('%.6f', $time_optimized / $iterations) . " 秒\n"; echo "性能提升: " . sprintf('%.1f', ($time_unoptimized / $time_optimized) * 100) . "%\n";
|