2016-12-26 154 views
0

我正在研究一個「簡碼」功能來替換保存在數據庫中的文本中的內容。PHP正則表達式替換括號內的內容

我試圖找到所有出現在雙括號內的任何東西{{ }},看看是否存在替換,如果有,替換它。我對正則表達式不好,我不知道這是否是這樣做的最有效的方法:

$string = "This is a {{test}} to see if it {{works}}"; 
$regex = ""; // Unfortunately, I'm clueless when it comes to regex 

preg_match_all($regex, $string, $matches); 

$replacements = array(
    'test' => 'sample', 
    'works' => 'exists' 
); 

foreach ($matches as $match) { 

    if (array_key_exists($match, $replacements)) { 
     $string = str_replace($match, $replacements[$match], $string);   
    } 

} 

return $string; 

在這個例子中,我想回:

This is a sample to see if it exists

我如果「簡碼」不存在,只需簡單地將其保留在內容中即可。

+1

您可以測試你的表情[這裏](https://regex101.com/)。但是,如果你的替換和示例中的一樣簡單,那麼使用'str_replace()'(只需連接大括號到針)。否則,在這種情況下,我會使用'preg_replace_callback()'。 – shudder

+0

這是正則表達式''/\{\{(.*?)\}\}/' – Robert

+0

@JROB如果這是爲了處理短代碼的目的,你可以使用我的Shortcode庫:https://github.com/thunderer/使用默認處理程序和自定義語法對象進行簡碼,該對象將根據所需數組檢測並替換所有內容。 –

回答

1

你可以這樣做:

$string = "This is a {{test}} to see if it {{works}}"; 
$regex = "|\{\{(.*)\}\}|"; 

$replacements = [ 
'test' => 'sample', 
'works' => 'exists' 
]; 

preg_replace_callback($regex, function($matches) use($replacemnets) { 
    if (isset($replacements[$matches[0]]) { 
    return $replacements[$matches[0]; 
    } 
    else { 
    return $matches[0]; 
    } 
}, $string); 
1

如果您事先知道使用雙大括號括起來的關鍵字,您甚至不需要正則表達式。到str_replace()一個簡單的調用就足夠了:

$string = "This is a {{test}} to see if it {{works}}"; 

$replacements = array(
    '{{test}}' => 'sample', 
    '{{works}}' => 'exists', 
); 

$text = str_replace(array_keys($replacements), array_values($replacements), $string); 

但是,如果你要替換所有關鍵字,即使是那些你不具備,正則表達式是不可避免的,功能preg_replace_callback()來救援的替代品:

$string = "This is a {{test}} to see if it {{works}}"; 

$replacements = array(
    '{{test}}' => 'sample', 
    '{{works}}' => 'exists', 
); 

$text = preg_replace_callback(
    '/\{\{[^}]*\}\}/', 
    function (array $m) use ($replacements) { 
     return array_key_exists($m[0], $replacements) ? $replacements[$m[0]] : ''; 
    }, 
    $string 
); 

因爲{}special characters正則表達式,他們需要爲了escaped被解釋爲普通字符(而忽略其特殊含義)。

每當正則表達式匹配字符串的一部分時,就會調用anonymous function(回調函數)。 $m[0]始終包含與整個正則表達式匹配的字符串部分。如果正則表達式包含subpatterns,則匹配每個子模式的字符串部分可在$m的各個位置獲得。在我們使用的表達式中沒有子模式,$m在索引0處包含單個值。

回調函數返回的值用於替換匹配整個表達式的字符串部分。

相關問題