【发布时间】:2019-03-10 15:12:40
【问题描述】:
我想找到一个模式{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);
和我的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;
}
预期输出
你会有一个这样格式的记事本来做 PHP
如何在 php 中使用正则表达式同时使用 preg_replace_callback 替换文本和花括号
【问题讨论】:
-
将
special_functions代码添加到问题中并提供预期结果。 -
预期输出是什么?
-
@revo 更新了我的问题
-
@WiktorStribiżew 我已将功能添加到我的问题中
-
请看下面我的回答,它一定对你有用。如果没有,请提供一个更新的 PHP fiddle 来显示问题。
标签: php regex preg-replace-callback