[英]How can i replace a line of php code with preg_replace
I have the following line of php code in some of my pages 我的某些页面中有以下PHP代码行
<?php include("contactform.php"); ?>
I have a crude CMS where I exchange lines of code for user manageable tags, my hope is to convert this line of code into [contact] so that people can add or remove it at their leisure. 我有一个粗略的CMS,我在其中交换用户可管理标签的代码行,我希望将这行代码转换为[contact],以便人们可以随意添加或删除它。 This is how far i've got...
这就是我要走的路...
ie $file = preg_replace('#<?php include("contactform.php"); ?>#i', "[contact]", $file);
即
$file = preg_replace('#<?php include("contactform.php"); ?>#i', "[contact]", $file);
$file looks something like this... $ file看起来像这样...
<h1 class="title">Title</h1>
<p>Text</p>
<?php include("contactform.php"); ?>
So the PHP code has not been stripped out by the server as we are editing the file and not viewing it. 因此,在我们编辑文件而不查看文件时,服务器尚未剥离PHP代码。
I'm pretty new to PHP so I guess i'm being really stupid, is there a way to do this? 我对PHP还是很陌生,所以我想我真的很傻,有没有办法做到这一点?
If you want to do 1:1 string replacements, then use the simpler str_replace
如果要进行1:1字符串替换,请使用更简单的
str_replace
$file = str_replace('<?php include("contactform.php"); ?>', "[contact]", $file);
With a preg_replace you need to escape meta characters like ?
使用preg_replace,您需要转义类似
?
元字符 and (
with backslashes: 和
(
带反斜杠:
$file = preg_replace('#<\?php include\("contactform.php"\); \?>#i', "[contact]", $file);
And using a regex would only provide any advantage if you want to make it more resilient of whitespace for example. 例如,如果想使正则表达式更具弹性,则使用正则表达式只会提供任何优势。 Use
\\s+
instead of literal spaces in that case. 在这种情况下,请使用
\\s+
而不是文字空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.