0

I have the following line of php code in some of my pages

<?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. This is how far i've got...

i.e. $file = preg_replace('#<?php include("contactform.php"); ?>#i', "[contact]", $file);

$file looks something like this...

<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.


I'm pretty new to PHP so I guess i'm being really stupid, is there a way to do this?

1 Answer 1

3

If you want to do 1:1 string replacements, then use the simpler str_replace

$file = str_replace('<?php include("contactform.php"); ?>', "[contact]", $file);

With a preg_replace you need to escape meta characters like ? 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.