php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #70738 preg_replace_callback_array doesn't globally respect the $limit argument
Submitted: 2015-10-19 11:31 UTC Modified: 2019-03-18 14:58 UTC
From: nicolas dot grekas+php at gmail dot com Assigned:
Status: Wont fix Package: PCRE related
PHP Version: 7.0.0RC5 OS:
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: nicolas dot grekas+php at gmail dot com
New email:
PHP Version: OS:

 

 [2015-10-19 11:31 UTC] nicolas dot grekas+php at gmail dot com
Description:
------------
preg_replace_callback_array's $limit argument is used independently for all items in the $patterns array.

I'm not sure this is the behavior that it should have. It makes it possible for example to has $count > $limit. This is counter intuitive.

Test script:
---------------
echo preg_replace_callback_array(
    array(
        '/[^a]/' => function () {return 'a';},
        '/a/' => function () {return 'd';},
    ),
    'abca',
    3,
    $count
);

echo $count;

Expected result:
----------------
daaa3

Actual result:
--------------
ddda5

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2019-03-18 14:58 UTC] nikic@php.net
-Status: Open +Status: Wont fix
 [2019-03-18 14:58 UTC] nikic@php.net
This behavior is consistent with preg_replace_callback():

echo preg_replace_callback(
    array('/[^a]/', '/a/'),
    function () {return 'a';},
    'abca',
    3,
    $count
), "\n";
echo $count, "\n"; // 5

And for that matter also with preg_replace():

echo preg_replace(
    array('/[^a]/', '/a/'),
    'a',
    'abca',
    3,
    $count
), "\n";
echo $count, "\n"; // 5

Regardless of how this ought to have worked originally, I don't think it makes sense to change this at this point. The limit is for each replacement, rather than for all replacements together.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Tue May 13 13:01:27 2025 UTC