I want to add comment inside a replaced text only if condition is true.
This is the basic code I work with.
<?php
$keepcomments="yes"; //yes or no
$str="abcdefgh";
$str = preg_replace("~abcd~", 'dcba "if($keepcomments=="yes"){ echo"-- some comments here --"} ', $str);
echo $str;
?>
I tried with :
if ($keepcomments=="yes"){
$str = $str."<-- some comments here -->";
}
The result is :
dcbaefgh-- some comments here --
But I have to preg_replace
in more lines, problem is when I do that, all the comments are appearing at the end of result string.
dcbaefgh
dcbaefgh
dcbaefgh
-- some comments here --
-- some comments here --
-- some comments here --
and I don't know how to use preg_replace_callback()
in this case.
Any help would be appreciated.
EDIT
When the string is "abcdefgh", i want to replace "abcd" in that string with "dcba". at the same time, if $keepcomments
is yes, then i want to add a comment at the end of that string.
and then i want to duplicate same code in few more lines.
Expected output is :
dcbaefgh-- some comments here --
dcbaefgh-- some comments here --
dcbaefgh-- some comments here --