小编Sha*_*dow的帖子

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

我想找到一种模式{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 中同时替换文本和大括号

php regex preg-replace-callback

5
推荐指数
1
解决办法
357
查看次数

标签 统计

php ×1

preg-replace-callback ×1

regex ×1