I would like to preg_replace some text but only if it’s not commented. Here’s an example of a given text:
// delete_me('First');
delete_me('Second');
/* delete_me('Third'); */
delete_me('Fourth'); // Some comment behind a command.
/* Tiny bit of comment */ delete_me('Fifth');
Now in this example I would only want the second, fourth and fifth row to be replaced. I want to replace the parameter with a new one. All the text is in one big string, separated by newlines.
I do have some preg_replaces to remove comment sections, but since I don’t want to delete them it’s not much use, but perhaps it helps someone helping me.
$text = preg_replace("/\/\/(.*)/", $replace, $text);
$text = preg_replace('!/\*(.*)\*/!s', $replace, $text);
Can anyone help me to replace the given parameters on lines that are not PHP commented? Thanks!
First split the text into chunks of comment and non-comment, then only alter the non-comment pieces, and finally glue them together:
output:
The trick here is that the pattern supplied to
preg_splitmatches the comment blocks, so you get an array of even/odd pieces of code/comment.caveat This will of course break when you would put
/*in a string literal.