How do I use PHP preg_replace_callback?
I’m working on a project that sends transactional emails from templates using variables in the %%varname%% format, but defines variables in another table as a lookup value, or query. So, I needed to match strings of type %%varname%% which screams regular expressions, but also needed varname to look up what to replace it with. So, instead of using multiple functions, I was able to do this with a callback and preg_replace_callback.
<?php $string = "A complicated gentleman allow me to present, Of all %%asdf%% the arts and faculties the terse embodiment, He's a great arithmetician who can demonstrate with ease %%name%% That two and two are three, or five, or anything you please; An eminent Logician who can make it clear to you That black is white – when looked at from the proper point of view; A marvelous Philologist who'll undertake to show %%asdf%% That 'yes' is but another and a neater form of 'no'."; echo preg_replace_callback('(%%.*%%)', create_function( '$matches', 'return getValue($matches)' ), $string ); function getValue($var) { return toupper(str_replace('%%', '', $var)); } /* Outputs: A complicated gentleman allow me to present, Of all ASDF the arts and faculties the terse embodiment, He's a great arithmetician who can demonstrate with ease NAME That two and two are three, or five, or anything you please; An eminent Logician who can make it clear to you That black is white – when looked at from the proper point of view; A marvelous Philologist who'll undertake to show ASDF That 'yes' is but another and a neater form of 'no'. */
I use the function getValue to query the database and get the value of the variable. This function is pretty slick; now, PHP just needs to support callbacks that aren’t created as strings and we’ll be all set.