Search code examples
phppreg-replacepreg-replace-callback

Accessing global state in PHP using preg_replace_callback() callbacks


I've got a piece of text, for example:

XYZ id dui vel erat bibendum hendrerit aliquet ac lorem. Integer ABC turpis, facilisis sit amet ultricies non, tempor LMNOP est. Aliquam sit amet sapien justo. Quisque TUV dolor dolor, eu sodales mi.

I need to replace the bolded words with numbered placeholders.

%%%1%%% id dui vel erat bibendum hendrerit aliquet ac lorem. Integer %%%2%%% turpis, facilisis sit amet ultricies non, tempor %%%3%%% est. Aliquam sit amet sapien justo. Quisque %%%4%%% dolor dolor, eu sodales mi.

Doing this replacement, I need to store into an array the text it's replacing (e.g. XYZ) and keyed to the number of the placeholder (e.g. 1), such that I can go back and swap them back out with the original values later on.

The difficult part is that I don't know the replacement text in advance, so I need a callback to generate it based on the current count of items that have been replaced already.

I am running on an older version of PHP and do not have anonymous functions available in my toolkit, so I believe I am limited to callbacks using preg_replace_callback. It seems my problem boils down to the fact that I need the functions I create (using create_function) to be able to access some shared global state -- at the very least a shared global array where I can push and pop text that was replaced onto the stack.

Is this possible?


Solution

  • Instead of using create_function() you will find it easier to make a regular function. (It's just easier not to have to deal with the complicated string escaping needed.)

    Use global $var; to set a global.

    Then after running your replace access that global (if the replace call is in a function you will need to say global $var; there as well).