温馨提示×

php preg_replace_callback 如何捕获组

PHP
小樊
82
2024-06-24 20:11:26
栏目: 编程语言

在 PHP 中使用 preg_replace_callback() 函数时,可以通过在回调函数中使用参数 $matches 来捕获组的内容。$matches 是一个数组,包含正则表达式匹配的结果。

下面是一个示例代码,演示如何捕获组的内容:

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

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

echo $result;

在上面的代码中,我们使用正则表达式 /(\w+)\s(\w+)/ 匹配文本中的第一个和第二个单词,并在回调函数中将它们合并为一个大写字符串。可以通过 $matches 数组来访问捕获到的组的内容。

0