Php 在preg_replace中使用卷曲大括号

Php 在preg_replace中使用卷曲大括号,php,preg-replace,Php,Preg Replace,我正在尝试使用preg_replace来更改TeX文件的格式 这是我的代码: $regex = "#([\][A-Za-z]+)(Title)#e"; $replace = "('hl\{$1Title}')"; $newphrase = preg_replace($regex,$replace,$newphrase); 我的问题是,{前面的“\”会在我的输出中打印出来 像这样:\hl\{FaithTitle}而不是这个:\hl{FaithTitle} 我尝试了很多不同的方法,这里有几个: $

我正在尝试使用preg_replace来更改TeX文件的格式

这是我的代码:

$regex = "#([\][A-Za-z]+)(Title)#e";
$replace = "('hl\{$1Title}')";
$newphrase = preg_replace($regex,$replace,$newphrase);
我的问题是,{前面的“\”会在我的输出中打印出来

像这样:\hl\{FaithTitle}而不是这个:\hl{FaithTitle}

我尝试了很多不同的方法,这里有几个:

$replace = "('hl{$1Title}')";
那一个使整个页面崩溃

$replace = "('hl[{]$1Title}')";
那个打印出方形和卷曲的大括号


我将非常感谢您的帮助!

您的正则表达式没有做您认为它正在做的事情

由于
\
,您的字符类实际上与
A-Za-z
匹配,但也与
][
匹配,因为
\
转义了
]
的含义,并且
[
在类内没有任何字符

试试这个:

$regex = "#(\\[A-Za-z]+)(Title)#";

同时删除
e
修饰符。我不知道你为什么要把它放在那里,但这可能就是它崩溃的原因。

最初的短语是什么?我的意思是你写了预期结果
\hl{FaithTitle}
但是在
preg_replace
调用中缺少了
$newphrase
的定义。$newphrase变量中有很多内容,但这里是它的一部分:
962005)和\textit{\FaithTitle}(1977,1988)都是由
$regex=“#([\\a-Za-z]+)(Title);$replace=“hl{\$1Title}”
这就是我最终得到的结果,而且它是有效的!我修改的示例代码中包含了
e
修饰符……感谢您的支持!