带有preg_replace_callback的DIY PHP短代码?

时间:2016-12-21 05:10:16

标签: php regex 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.

1 个答案:

答案 0 :(得分:2)

函数 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] =&gt; [与会者]
      [1] =&gt;与会者
  )
  阵列
  (
      [0] =&gt; [日]
      [1] =&gt;天
  )
  阵列
  (
      [0] =&gt; [员工姓名]
      [1] =&gt;员工姓名
  )
  
  亲爱的沃伦,我们期待着在周一见到你。问候,约翰。