2017-08-07 165 views
0

我寫了一個函數來替換博客中的某些模式。例如,當有人輸入::)此功能用笑臉表情符號代替。如何在preg_replace()中調用函數?

但是現在我正在嘗試做一些特別的事情,但不知道如何完成它。我想匹配解析到另一個功能,像這樣:

$pattern[] = "/\[ourl\](.*?)\[\/ourl\]/i"; 
$replace[] = "" . getOpenGraph("$1") . ""; 
$value = preg_replace($pattern, $replace, $value); 

如果有人使用[ourl] www.cnn.com [/ ourl]這個功能將檢索OpenGraph信息,並返回一個特定的HTML代碼。

但是這不起作用,因爲它不會解析函數$1

我該如何解決這個問題?

UPDATE:

根據提示u_mulder給我,我能夠把它關閉

+1

'preg_replace_callback' –

+0

甚至['preg_replace_callback_array'](http://php.net/manual/en/function.preg-replace-callback-array.php ) –

+0

@WiktorStribiżew哇,但它只是php7。 –

回答

1

我創建了一個示範,展示如何調用getOpenGraph()以及如何將捕獲組作爲參數傳遞,而不在preg_replace_callback()的第二個參數中指定它們。

我修改了模式分隔符,以便不需要轉義結束標記中的斜線。

function getOpenGraph($matches){ 
    return strrev($matches[1]); // just reverse the string for effect 
} 

$input='Leading text [ourl]This is ourl-wrapped text[/ourl] trailing text'; 
$pattern='~\[ourl\](.*?)\[/ourl\]~i'; 
$output=preg_replace_callback($pattern,'getOpenGraph',$input); 
echo $output; 

輸出:

Leading text txet depparw-lruo si sihT trailing text 
0

試試這個:

<?php 

$content = "[ourl]test[/ourl]\n[link]www.example.com[/link]"; 
$regex = "/\[(.*)\](.*?)\[(\/.*)\]/i"; 

$result = preg_replace_callback($regex, function($match) { 
    return getOpenGraph($match[1], $match[2]); 
}, $content); 

function getOpenGraph($tag, $value) { 
    return "$tag = $value"; 
} 
echo $result;