我正在研究一个“简码”功能来替换保存在数据库中的文本中的内容。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
我如果“简码”不存在,只需简单地将其保留在内容中即可。
您可以测试你的表情[这里](https://regex101.com/)。但是,如果你的替换和示例中的一样简单,那么使用'str_replace()'(只需连接大括号到针)。否则,在这种情况下,我会使用'preg_replace_callback()'。 – shudder
这是正则表达式''/\{\{(.*?)\}\}/' – Robert
@JROB如果这是为了处理短代码的目的,你可以使用我的Shortcode库:https://github.com/thunderer/使用默认处理程序和自定义语法对象进行简码,该对象将根据所需数组检测并替换所有内容。 –