2016-12-21 98 views
1

我知道preg_replace_callback對於這個目的是理想的,但我不知道如何完成我開始的工作。使用preg_replace_callback DIY PHP短代碼?

你可以看到我想要實現 - 我只是不知道如何使用回調函數:

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

回答

2

功能preg_replace_callback在第一個參數($ matches)中提供了一個數組。
對於您的情況,$匹配[0]包含整個匹配的字符串,而$匹配[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] =>人員名


親愛的沃倫,我們期待週一見到你。問候,約翰。