php / php/php-src

preg_replace_callback $count number of matches, number of replacements

オープン
#20,589 コメント 4 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

Bug Extension: pcre Status: Needs Triage
主要言語
C
スター
40.4k
フォーク
8.2k
平均マージ
2日 13時間
マージ済み PR(30日)
96

説明

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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、リンクされた PHP 8.5 の例を再現し、preg_replace と preg_replace_callback を比較します。preg_replace のドキュメントを読み、既存の count が置換回数としてどのように定義されているかを追跡します。マッチ数と置換数についてプロジェクトの方針が決定され、文書化され、リンクされた callback の制限が対処された時点で、issue は完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
php
領域
backend
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。