在PHP中,正則表達式中的反向引用允許您引用之前捕獲的分組。要使用反向引用,請在正則表達式中使用\n
(其中n是分組的編號)。分組是用圓括號()
創建的。
這是一個簡單的示例,說明如何在PHP中使用反向引用:
<?php
$text = "The quick brown fox jumps over the lazy dog";
preg_match_all('/(\w+)\s+(\w+)/', $text, $matches);
// $matches[0] 包含 "The quick"
// $matches[1] 包含 "brown"
// $matches[2] 包含 "fox jumps"
// $matches[3] 包含 "over the"
// $matches[4] 包含 "lazy dog"
// 使用反向引用將第二個單詞與第一個單詞組合
foreach ($matches[0] as $key => $match) {
if ($key % 2 == 1) { // 只選擇奇數索引(從0開始)的匹配項
$matches[$key] = $matches[0][$key - 1] . ' ' . $match;
}
}
print_r($matches);
?>
輸出:
Array
(
[0] => Array
(
[0] => The quick brown fox jumps over the lazy dog
)
[1] => Array
(
[0] => quick brown fox jumps over the lazy dog
)
)
在這個示例中,我們使用正則表達式/(\w+)\s+(\w+)/
捕獲了兩個單詞分組。然后,我們遍歷匹配項,并使用反向引用將第二個單詞與第一個單詞組合在一起。