Replacing Placeholder Variables Using Regular Expressions
5 Nov2007
I recently had to take a string with some delimited values as placeholders and replace them with variables from an array. This is useful for things like sending out email newsletters or SMS messages with people's names or other unique information in each message.
An example of a string with placeholders in it, using the string '%%' as a delimeter is:
Hello %%NAME%%, your %%CAR%% is ready to pickup from %%STORE%%
Now take an array with some key/value pairs:
The following code will perform the replacement based on the filter:
The interesting parts of the above code are, in the pattern:
the "?" makes this a "non-greedy" match, meaning that it won't match everything in between the first and last occurence of $delim. Using "?" in this way allows you to make individual matches non-greedy. You can also use the /U modifier at the end of the expression to make all matches non greedy:
The next interesting bit is the fact that the second argument to preg_replace_callback can be an array with an object and a method. This allows you to use preg_replace_callback in your OO based PHP application without breaking out into procedural code (cos where would you put it!?).
This entry was posted on Monday, November 5th, 2007 at 7:03 pm author iain dooley, php, recipe, recipes, regex
Subscribe
Building software in the real world - the Working Software blog
We write about our experiences, ideas and interests in business, software and the business of software. We also sometimes write about our own products (in order to promote them).
Recent Posts
- RSS is only dead if we let it die
- Kill your index.php
- 18 Things I Wish I Knew 7 Years Ago
- When does automation become coding
- A list of things you can do to afford Mixergy Premium in 2012
- Thanks Louis now here is my dad
- Your templating engine sucks and everything you have ever written is spaghetti code yes you
- Energy for Opportunity website is now live
- Escaping single and double quotes in XPath queries in PHP
- The reason that outsourcing software is so difficult