php preg_replace_callback 如何捕獲組

PHP
小樊
84
2024-06-24 20:11:26

在 PHP 中使用 preg_replace_callback() 函數(shù)時(shí),可以通過(guò)在回調(diào)函數(shù)中使用參數(shù) $matches 來(lái)捕獲組的內(nèi)容。$matches 是一個(gè)數(shù)組,包含正則表達(dá)式匹配的結(jié)果。

下面是一個(gè)示例代碼,演示如何捕獲組的內(nèi)容:

$text = 'Hello, my name is John Doe.';
$pattern = '/(\w+)\s(\w+)/';

$result = preg_replace_callback($pattern, function($matches) {
    // $matches[0] 匹配到的整個(gè)字符串
    // $matches[1] 匹配到的第一個(gè)組
    // $matches[2] 匹配到的第二個(gè)組
    $name = $matches[1] . ' ' . $matches[2];
    
    return strtoupper($name);
}, $text);

echo $result;

在上面的代碼中,我們使用正則表達(dá)式 /(\w+)\s(\w+)/ 匹配文本中的第一個(gè)和第二個(gè)單詞,并在回調(diào)函數(shù)中將它們合并為一個(gè)大寫(xiě)字符串??梢酝ㄟ^(guò) $matches 數(shù)組來(lái)訪問(wèn)捕獲到的組的內(nèi)容。

0