Question

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?

Was it helpful?

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).

OTHER TIPS

You can always pass in a class method and use the instances properties (just look at the callback type). The global keyword is a possibility as well if it fits your situation better.

If you're using PHP 5.3, you can create a closure and import locally scoped data within the callback. This avoids the messiness of global data while allowing your callbacks to access the data that it needs. See the following for a trivial example

<?php
// The data you want to use in your function
$data = array(/* ... whatever ... */);

$val = preg_replace_callback('/regex/', function ($matches) use ($data) {
    /* do stuff here with $data and $matches */
});
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top