Question

I have a file that contains several colors as hexadecimals (i.e. #000 or #ffffff) and I'm trying to replace each of them with @varN where N is a number that increments with each replacement done. I believed my code does that, but $count always returns 196 after doing the placement even though I put the limit to 1 so count should never goes past 1. This results an endless loop. Why isn't it the limit working and what I can do to get the desired output?

$list = file($filepath.$file, FILE_USE_INCLUDE_PATH);
$pattern = "/#((([a-f]|[A-F]|[0-9]){6})|(([a-f]|[A-F]|[0-9]){3}))/";
$replaceVar = "@var";
$replaceNum = 0;
$count = 1;
while($count != 0){ //never ends
    $replacement = $replaceVar.$replaceNum;
    $output = preg_replace($pattern,$replacement,$list,1,$count);
    $replaceNum++;
    echo $replaceNum." ".$count."\n"; //returns $replaceNum and 196
}
file_put_contents($filepath.'/new'.$file,$output,FILE_USE_INCLUDE_PATH);

Example input file:

#000000 #111111 #123456 #abcdef #123 #abc

Example output file:

@var1 @var2 @var3 @var4 @var5 @var6

Was it helpful?

Solution

You don't use the good function to do that for several reasons, I suggest you to use preg_replace_callback instead. Example:

$source = file_get_contents($yourfile);

$pattern = '~#[[:xdigit:]]{3}(?:[[:xdigit:]]{3})?~';
$count = 0;

$output = preg_replace_callback($pattern,
                       function ($m) use (&$count) { return '@var' . ++$count; },
                                $source);

OTHER TIPS

You are always replacing on $list, but writing the result of the replacement to $output:

$output = preg_replace($pattern,$replacement,$list,1,$count);

This means, your $list will ALWAYS contain 1 match, when it starts with 1 - its never modified. Therefore your while will run without an end. You have to REPLACE it inside the same string you are scanning for more hits:

$list = preg_replace($pattern,$replacement,$list,1,$count);

now - at one point - $count should become zero, and $list contain no more unwanted matches.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top