I need to do a preg_replace on all of the PHP tags in a string, as well as any characters sitting between the PHP tags.
Eg, if the file contents was:
Hey there!
<?php some_stuff() ?>
Woohoo!
All that should be left is:
Hey there!
Woohoo!
Here’s my code:
$file_contents = file_get_contents('somefilename.php');
$regex = '#([<?php](.*)[\?>])#e';
$file_contents = preg_replace($regex, '<<GENERATED CONTENT>>', $file_contents);
FAIL.
My regular expression skills are poor, can someone please fix my regex. Thank you.
Try this regex:
Should work on short tags (without ‘php’) too.
I think the main issue with your attempt was that you need to escape the question marks with backslashes, and that you were using square brackets where you shouldn’t have been. Square brackets means “pick any one of these characters”.