用 preg_replace_callback DIY PHP 简码?

DIY PHP shortcode with preg_replace_callback?

我知道 preg_replace_callback 非常适合此目的,但我不确定如何完成我已经开始的工作。

您可以看到我正在努力实现的目标 - 我只是不确定如何使用回调函数:

//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;

所需的输出将是 Dear Warren, we are looking forward to seeing you on Monday. Regards, John.

函数preg_replace_callback在第一个参数($matches)中提供了一个数组。
在您的情况下, $matches[0] 包含整个匹配的字符串,而 $matches[1] 包含第一个匹配组(即名称要替换的变量)。
回调函数应该return匹配字符串对应的变量值(即括号中的变量名)

所以你可以试试这个:

<?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;
?>

这会给...

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.