Re: Re: [PROPOSAL]Add second to callback of preg_replace_callback

From: Date: Sat, 04 May 2013 12:58:58 +0000
Subject: Re: Re: [PROPOSAL]Add second to callback of preg_replace_callback
References: 1 2 3 4  Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
On Sat, May 4, 2013 at 2:52 PM, Laruence <[email protected]> wrote:

>
>
>
> On Sat, May 4, 2013 at 8:49 PM, Nikita Popov <[email protected]> wrote:
>
>> On Sat, May 4, 2013 at 2:39 PM, Laruence <[email protected]> wrote:
>>
>>> Hey:
>>>    Sorry for the delay,  the new patch, which make the second argument
>>> the
>>> regex array keys is attached.
>>>
>>>
>>>
>>> https://bugs.php.net/patch-display.php?bug_id=64730&patch=second_arg_rege_key.patch&revision=latest
>>>
>>>    with this patch,  preg_replace_callback will call user callback with
>>> two
>>> arguments, the first one is the same,  the second is the regex key if the
>>> regex is an array or NULL if the regex is a string.
>>>
>>>    then we can do something like:
>>>
>>>     $code = preg_replace_callback(
>>> array(
>>> "foo" => "/some very complex regex/",
>>> "bar" => "/another one/",
>>> ...
>>> ),
>>> function($matches, $idx)  {
>>>  switch ($idx) {
>>>   case 'foo'
>>>     ...
>>>   case 'bar':
>>>     ...
>>>  }
>>> },
>>> $code);
>>>
>>>
>>>   if no objections,  I will commit this patch after 5.5. 0 final
>>> release..
>>>
>>>   thanks
>>>
>>
>> I object. If this were using the preg_replace_callback(Array, Array,
>> String) syntax [which is not practically possible due to ambiguity], I
>> would agree that this is a nice feature which makes the function consistent
>> with preg_replace and str_replace. But this implementation with some weird
>> additional identifier that you need to switch over makes absolutely no
>> sense to me and only complicated the API. Better to just use a loop for
>> this.
>>
> if you got an better solution, please propose it.
>
> only object won't help much here, since the problem is there, we need to
> solve it.
>
> thanks
>

Sorry, but what problem is there again? As I already said earlier, you can
just use a loop:

foreach ($replacements as $regex => $callback) {
    $str = preg_replace_callback($regex, $callback, $str);
}

Which is both clearer and requires less code.

Nikita


Thread (22 messages)

« previous php.internals (#67295) next »