2016-12-26 157 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处包含单个值。

回调函数返回的值用于替换匹配整个表达式的字符串部分。

相关问题