Question

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 --
Was it helpful?

Solution

Use a callback function:

$str = preg_replace_callback("~(abcd)(.*)~", function($match) use ($keepcomments) {
    $r = strrev($match[1]) . $match[2];

    if ($keepcomments == 'yes') {
        return $r . '-- some comments here --';
    } else {
        return $r;
    }
}, $str);

OTHER TIPS

$str=array("abcdefgh","dfgvdfg","rgerhg");

foreach($str as &$row)
{
if ($keepcomments=="yes"){ 
$row= $row."<-- some comments here -->";


}
}

This answer from jack did the trick : https://stackoverflow.com/a/22777242/1940720

i had to change something. i submit the final answer here, maybe it will help someone.

$str = preg_replace_callback("~(replace-string-here)(.*)~", function($match) use ($keepcomments) {
    if ($keepcomments == 'yes') {
        return  'string -- comments -- ';
    } else {
        return 'string';
    }
}, $str);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top