I am looking for a little help with regular expressions in PHP. I have used them a bit before but not really to this extent. What I want to do is, parse a string and look for pattern matches in a certain format, in this case being %GETVALUE#% (Where # is a number) and then replace these patterns with values retrieved from the database. The only catch is that the number that is placed where the #'s are is the ID of the record I would like to retrieve from the database.

I am finding this a little difficult to explain so I think an example is in order:

$inputString = "The number 1 in words is %GETVALUE1%. %GETVALUE2% is the number 2 in words.";

// Database table
id    value
1     One
2     Two

// Expected return = "The number 1 in words is One. Two is the number 2 in words."

I could write a regular expression to match both of the tags i.e. /%GETVALUE\s*(\d)+%/ (At a guess, would possibly need to fiddle with it), though my main problem is that I am not sure how to go about grabbing the # part of %GETVALUE#%. If I could do that then I'm sure I could churn out something that does the trick.


Brilliant, I think that is just what I am looking for. Thanks a lot.