[php-src] Issue #20589: preg_replace_callback $count number of matches, number of replacements

From: Date: Tue, 25 Nov 2025 15:22:08 +0000
Subject: [php-src] Issue #20589: preg_replace_callback $count number of matches, number of replacements
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-251307@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/20589 Author: kkmuffme ### Description The following code: https://3v4l.org/0E8mn#v8.5.0 ```php <?php $before = 'abca'; $after = preg_replace( '/a/', 'a', $before, -1, $count ); if ( $after === $before ) { echo "NO REPLACEMENTS" . PHP_EOL; } echo $count . " REPLACEMENTS"; ``` Resulted in this output: ``` NO REPLACEMENTS 2 REPLACEMENTS ``` But I expected this output instead: ``` NO REPLACEMENTS 0 REPLACEMENTS ``` https://www.php.net/manual/en/function.preg-replace.php >If specified, this variable will be filled with the number of replacements done. Technically, this is correct, since the replacement is identical to the search string. While for preg_replace this makes practically no difference (except for cases where backslash is incorrectly escaped, you could end up with a preg that says it replaced even though it didn't change the input) Practically for preg_replace_callback this means however, that you always have to compare before/after to be sure whether anything was replaced at all. And there's no way of knowing how many replacements were actually done. Changing the behavior should generally be safe I guess, but otherwise just adding an additional param "$replacement_count" for preg_replace_callback would make sense? (so the 1st param docs would be changed to be "number of matches") ### PHP Version ```plain 8.5 ``` ### Operating System _No response_

« previous php.bugs (#251307) next »