2011-12-17 88 views
0

創建模板我有一個字符串,它看起來是這樣的:正則表達式替換PHP

{{imagename.jpg|left|The caption for this image. Includes a variety of chars}} 
<p>Some text, lots of paragraphs here.</p> 
{{anotherimage.jpg|right|Another caption.}} 

我試圖做的是分析出{{}}位,然後通過函數傳遞參數。我至今是:

function template_function($matches) { 
    print_r($matches); 
} 

function parse_images($string) { 
    $string = preg_replace_callback('!\{\{([^}])\}\}!', 'template_function', $string); 
    return $string; 
} 

能有人給我一隻手用正則表達式,使我最終被通過print_r運行比賽嗎?

回答

1
function template_function($matches) { 
    print_r($matches[1]); 
} 

function parse_images($string) { 
    $string = preg_replace_callback('/\{\{([^}]*)\}\}/', 'template_function', $string); 
    return $string; 
} 

也已修改print_r($matches[1]);使得實際匹配被打印。

+0

所以,我錯過了流血*!我知道我必須快到了!這就是爲什麼Stack Overflow非常棒 - 讓別人瀏覽你的代碼非常有用。 – 2011-12-17 21:27:09

1

您錯過了*(或可能是+)量詞。你的原始表情只會匹配一個單一的非}字符。

$string = preg_replace_callback('!\{\{([^}]*)\}\}!', 'template_function', $string);