I understand that preg_replace_callback is ideal for this purpose, but I'm not sure how to finish what I've started.
You can see what I'm trying to achieve - I'm just not sure how to use the callback function:
//my string
$string = 'Dear [attendee], we are looking forward to seeing you on [day]. Regards, [staff name]. ';
//search pattern
$pattern = '~\[(.*?)\]~';
//the function call
$result = preg_replace_callback($pattern, 'callback', $string);
//the callback function
function callback ($matches) {
echo "<pre>";
print_r($matches);
echo "</pre>";
//pseudocode
if shortcode = "attendee" then "Warren"
if shortcode = "day" then "Monday"
if shortcode = "staff name" then "John"
return ????;
}
echo $result;
The desired output would be Dear Warren, we are looking forward to seeing you on Monday. Regards, John.
The function preg_replace_callback provides an array in the 1st parameter ($matches).
In your case, $matches[0] contains the entire matched string, while $matches[1] contains the 1st matching group (i.e. the name of the variable to replace).
The callback function should return the variable value corresponding to the matching string (i.e. the variable name in brackets).
So you could try this:
This will give...