tags:

views:

65

answers:

3

I am trying to create a database field merge into a document (rtf) using php

i.e if I have a document that starts

Dear Sir,

Customer Name: [customer_name], Date of order: [order_date]

After retrieving the appropriate database record I can use a simple search and replace to insert the database field into the right place.

So far so good.

I would however like to have a little more control over the data before it is replaced. For example I may wish to Title Case it, or convert a delimited string into a list with carriage returns.

I would therefore like to be able to add extra formatting commands to the field to be replaced. e.g.

Dear Sir,

Customer Name: [customer_name, TC], Date of order: [order_date, Y/M/D]

There may be more than one formatting command per field.

Is there a way that I can now search for these strings? The format of the strings is not set in stone, so if I have to change the format then I can.

Any suggestions appreciated.

+1  A: 

You could use a templating system like Smarty, that might make your life easier, as you can do {$customer_name|ucwords} or actually put PHP code in your email template.

webdestroya
That sound like the sort of functionality I require, but I'm not outputting the document, but putting it back into a rtf editor. Are there any classes that would do this?
Dave
You could use smarty with output buffering.
Josh
A: 

You can use explode on it to separate them into array values.

For Example:

$customer_name = 'customer_name, TC';
$get_fields = explode(',', $customer_name);

foreach($get_fields as $value)
{
  $new_val = trim($value);
  // Now do whatever you want to these in here.
}

Sorry if I'm not understanding you.

SoLoGHoST
my problem is I don't know what to explode as it will change dynamically, I may have 'customer_name, TC' or 'customer_name, UC' or something completely different. I was wondering whether I could search for some sort of matching brackets?
Dave
@Dave: Try a regex
Josh
A: 

Try a RegEx and preg_replace_callback:

function replace_param($matches)
{
  $parts = explode(',',$matches[0]);
  //$parts now contains an array like: customer_name,TC,SE,YMD
  // do some substitutions and:
  return $text;
}
preg_replace_callback('/\[([^\]]+)\]/','replace_param',$rtf);
Josh
Josh, thanks, that looks really interesting, and the sort of thing that I was after. Will this parse the whole file finding multiple matches, or will I have to do some sort of looping?
Dave
I believe that will find every match calling replace_param() on each one.
Josh
Thanks, I've given it a test and it works well. I got an error to start with and found that I needed to use forward slashes around the regex i.e.preg_replace_callback('/\[([^\]]+)\/]','replace_param',$rtf);
Dave
That was a silly mistake on my part, sorry! I've corrected my answer.
Josh