【问题标题】:DIY PHP shortcode with preg_replace_callback?使用 preg_replace_callback DIY PHP 短代码?
【发布时间】:2017-05-06 10:45:45
【问题描述】:

我知道 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.

【问题讨论】:

    标签: php regex preg-replace-callback


    【解决方案1】:

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

    所以你可以试试这个:

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

    这会给...

    数组
    (
    [0] => [参加者]
    [1] => 与会者
    )
    数组
    (
    [0] => [天]
    [1] => 一天
    )
    数组
    (
    [0] => [员工姓名]
    [1] => 员工姓名
    )

    亲爱的沃伦,我们期待在星期一见到你。问候,约翰。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-06
      • 2016-11-28
      • 2012-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-24
      • 2013-04-07
      相关资源
      最近更新 更多