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