DIY PHP shortcode with preg_replace_callback?

236 views Asked by At

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.

1

There are 1 answers

0
hherger On BEST ANSWER

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:

<?php

//my string
$string  = 'Dear [attendee], we are looking forward to seeing you on [day]. Regards, [staff name]. ';

// Prepare the data
$data = array(
    'attendee'=>'Warren',
    'day'=>'Monday',
    'staff name'=>'John'
);

//search pattern
$pattern = '~\[(.*?)\]~';

//the function call
$result = preg_replace_callback($pattern, 'callback', $string);

//the callback function
function callback ($matches) {
    global $data;

    echo "<pre>";
    print_r($matches);
    echo "\n</pre>";

    // If there is an entry for the variable name return its value
    // else return the pattern itself
    return isset($data[$matches[1]]) ? $data[$matches[1]] : $matches[0];

}

echo $result;
?>

This will give...

Array
(
[0] => [attendee]
[1] => attendee
)
Array
(
[0] => [day]
[1] => day
)
Array
(
[0] => [staff name]
[1] => staff name
)

Dear Warren, we are looking forward to seeing you on Monday. Regards, John.