PHP 对大写字母(德语字符)的正则表达式反向引用

PHP regex backreference to uppercase (german chars)

我想在 特定的正则表达式模式 之后搜索文本(匹配一个或两个单词后跟点和空格)。然后我使用 preg_replace 和反向引用。是否可以使反向引用包含的文本得到大写?

$teaser = "Special markup. This is the remaining text..."
$pattern = '/(^\w+\s\w+\.\s)|(^\w+\.\s)/i'; //match one or two words followed by dot and whitespace
$replacement = '<span style="color: red">'[=11=]'. '</span>'; //[=11=] is the backreference
$text = preg_replace( $pattern, $replacement, $teaser );

我的预期输出:

 SPECIAL MARKUP. This is the remaining text...


也试过使用,没有成功:

$replacement = '<span style="color: red">' . strtoupper( '[=13=]' ) . '</span>';

感谢帮助。

您好,它稍微复杂一些,但仍然很简单。使用 preg_replace_callback:

$text = preg_replace_callback('regex', function($m) {
    return str_to_upper($m[1]);
}, $caption);

因此在您的情况下,您应该能够输入:

$text = preg_replace_callback( $pattern , function ($m) {
    return '<span style="color: red">' . strtoupper( $m[1] ) . '</span>';
}, $teaser);

应该可以。

您想按照评论中的建议使用回调来实现此目的。

$str = "Special markup. This is the remaining text...";

$str = preg_replace_callback('~^\w+(?:\s\w+)?\.\s~', 
     function($m) {
         return '<span style="color: red">'.strtoupper($m[0]).'</span>';
      }, $str);

echo $str;

输出

<span style="color: red">SPECIAL MARKUP. </span>This is the remaining text...