如何替换PHP文件中的最后一个大括号
我试图使用一些正则表达式解析php代码,但我一直在研究如何使用preg_replace()将最后一个}替换为我想要的字符串。下面是一个示例代码:如何替换PHP文件中的最后一个大括号,php,regex,preg-replace,Php,Regex,Preg Replace,我试图使用一些正则表达式解析php代码,但我一直在研究如何使用preg_replace()将最后一个}替换为我想要的字符串。下面是一个示例代码: $data = '<?php class Myclass { function index() { } } // <- I want to replace that curly brace ?>'; $data = preg_replace('##is','// my new string he
$data = '<?php
class Myclass {
function index() {
}
} // <- I want to replace that curly brace
?>';
$data = preg_replace('##is','// my new string here',$data);
$data='';
$data=preg_replace(“##is”,“//我的新字符串在这里”,$data);
知道怎么做吗?找到最后一个大括号,并用字符串替换它后面的所有字符
使用搜索模式:“(\})[^\}]*$”
应该这样做:
$pattern = "(\})[^\}]*$";
preg_replace($pattern, $replaceWith, $subject);
找到最后一个大括号并用字符串仅替换大括号本身
使用这样的命令:\}(?。*\})
更多信息:查找最后一个大括号,并用字符串替换它后面的所有字符
使用搜索模式:“(\})[^\}]*$”
应该这样做:
$pattern = "(\})[^\}]*$";
preg_replace($pattern, $replaceWith, $subject);
找到最后一个大括号并用字符串仅替换大括号本身
使用这样的命令:\}(?。*\})
更多信息:使用
strpos
查找最后一个{
的位置,然后使用substr\u replace使用strpos
查找最后一个{
的位置,然后使用substr\u replace您也可以尝试:\>(*)>。<
@Noufal Ibrahim提出了更好的解决方案。我编写了一个实现此解决方案的函数
function _injectCodeInClassDefinition($classString, $newCode, $comment="automatic patcher") {
$replaceWith = "// BEGIN code injected by $comment\n$newCode\n// END code injected by $comment\n";
$pos = strrpos($classString, '}');
return substr_replace($classString, $replaceWith, $pos, 0);
}
用法示例(向类文件添加新函数)
@努法尔·易卜拉欣提出了一个更好的解决方案。我编写了一个实现此解决方案的函数
function _injectCodeInClassDefinition($classString, $newCode, $comment="automatic patcher") {
$replaceWith = "// BEGIN code injected by $comment\n$newCode\n// END code injected by $comment\n";
$pos = strrpos($classString, '}');
return substr_replace($classString, $replaceWith, $pos, 0);
}
用法示例(向类文件添加新函数)
请给出一个输入示例。请给出一个输入示例。此代码在最后一个大括号后删除字符串一旦替换出现问题,我们将使用负前瞻:\}(?。.*\})
此代码在最后一个大括号后删除字符串一旦替换出现问题,然后我们将使用一个负前瞻:\}(?。*\})