1

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.