php / php/php-src

preg_replace_callback $count number of matches, number of replacements

Open
#20,589 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Extension: pcre Status: Needs Triage
Dominant language
C
Stars
40.4k
Forks
8.1k
Avg merge
2d 13h
Merged PRs (30d)
96

Description

Description

The following code:

https://3v4l.org/0E8mn#v8.5.0

<?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
8.5
Operating System

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the linked PHP 8.5 example and compare preg_replace with preg_replace_callback. Read the preg_replace documentation and trace how the existing count is defined as replacements; the issue is complete when the project has a decided, documented behavior for match versus replacement counts and the linked callback limitation is addressed.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.