查找大括号内的文本并替换包含大括号的文本

Sha*_*dow 5 php regex preg-replace-callback

我想找到一种模式{text}并替换包括大括号的文本。

$data = 'you will have a {text and text} in such a format to do {code and code}';
$data= preg_replace_callback('/(?<={{)[^}]*(?=}})/', array($this, 'special_functions'),$data);
Run Code Online (Sandbox Code Playgroud)

我的special function包含回调代码来替换大括号和完全和有条件的文本。

public function special_functions($occurances){
        $replace_html = '';
        if($occurances){
            switch ($occurances[0]) {
                case 'text and text':
                    $replace_html = 'NOTEPAD';
                    break;
                case 'code and code':
                    $replace_html = 'PHP';
                    break;

                default:
                    $replace_html ='';
                    break;
            }
        }
        return $replace_html;
    }
Run Code Online (Sandbox Code Playgroud)

预期输出

你将有一个这样格式的记事本来执行 PHP

preg_replace_callback如何使用正则表达式在 php 中同时替换文本和大括号

Wik*_*żew 3

您需要像这样编辑模式:

$data = preg_replace_callback('/{{([^{}]*)}}/', array($this, 'special_functions'), $data);
Run Code Online (Sandbox Code Playgroud)

{{([^{}]*)}}模式将匹配:

  • {{-{{子串
  • ([^{}]*)- 第 1 组:除 和 之外的任何 0+ 个{字符}
  • }}- 一段}}文字

然后,在special_functions函数内部,替换switch ($occurances[0])switch ($occurances[1])。这$occurrances[1]是用模式捕获的文本部分([^{}]*)。由于整个匹配是{{...}}且捕获的是...,因此...用于检查 switch 块中可能的情况,并且大括号将被删除,因为它们被消耗(=添加到作为函数结果替换的匹配值preg_replace_callback) 。

请参阅PHP 演示