while循环中的preg_replace

Why this example wont work:

$string='1000000000000';

while($string=preg_replace('/(\d)((\d\d\d)+\b)/','$1,$2',$string)){}
echo $string."<br>";

It supposed that the loop is repeated untill is not more to match. Untill the regex fail. But no, the loop is never ending.

this alternative works:

$string='10000000000000';

while(preg_match("/(\d)((\d\d\d)+\b)/",$string)){
    $string=preg_replace("/(\d)((\d\d\d)+\b)/","$1,$2",$string);
    }
    echo $string."<br>";

My question is: the preg_replace function returns some TRUE/FALSE value when the regex can't still matching? If return False why in the first example the loop never stop. Ive tried with:

while((regex)!==FALSE)
while((regex)==TRUE)

and it dont work.

I dont care about the how to put commas, i wanna know about the preg_replace function

If someone can help me. would be great. thanks

The optional 5th parameter to preg_replace(), $count, should be used to track how many replacements were made.

Your loop could look like

do {
    $string = preg_replace('/(\d)((\d\d\d)+\b)/','$1,$2', $string, 1, $count);
} while ($count);

Or, alternatively, this regex will do the work in one step

 $string = preg_replace('/(?!^)(?=(?>\d{3})+$)/', ',', $string);

From the manual:

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or NULL if an error occurred.

So as long as no error occurs, your assignment will always evaluate as true (a string evaluates as true).

What you could do is compare the return value to the subject, if they are the same, no match was found:

while ($string != preg_replace('/(\d)((\d\d\d)+\b)/','$1,$2',$string))
{
  // a match was found
}

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or NULL if an error occurred.

http://php.net/manual/en/function.preg-replace.php

So, the code would need to be:

while(($string=preg_replace('/(\d)((\d\d\d)+\b)/','$1,$2',$string)) !== $string){}

...I think... not even sure if that's valid PHP...