【发布时间】:2015-02-11 15:17:08
【问题描述】:
我正在尝试实现一个管理界面,管理员可以在其中创建站点元标记形成的高级规则。
我有一个函数,它接受一个模板并将其中的占位符替换为 $registry 中的值,并在需要时应用修饰符。
$registy = array( 'profession_name' => 'actor', 'total_found' => 100, );
$result = preg_replace_callback('/\{([^{}:]+)(:[^{}:]+)?\}/', function($matches) use ($registry) {
$result = $registry[$matches[1]] ?: $matches[0];
if (in_array($matches[2], array(':ucfirst', ':strtolower', ':strtoupper', ':lcfirst')))
{
$result = call_user_func(substr($matches[2], 1), $result);
}
return $result;
},
$template);
例子:
职业 {name:ucfirtst} 是 {profession_name:strtoupper}
被分配到
职业名称是演员
我正在尝试实现条件,所以可以制定这样的规则:
条件前带有 {placeholders} 的文本。 [{total_found},带有 {placeholders} 的 TRUE 文本,带有 {placeholders} 的 FALSE 文本],条件后带有 {placeholders} 的尾随文本。
所以我的函数会从注册表中获取 {total_found} 值,并且取决于它是 true 还是 false 将返回带有相应 false 或 true 模式的字符串。 我不擅长正则表达式,不知道如何用正则表达式来写这个条件。 请帮帮我。
更新: 具体示例如下:
$template = 'Profession is {profession_name}. [{total_found}, {total_found} vacancies found, No vacancies found]. {profession_name} in your town';
在我的回调函数中,我会设置这样的条件
if ($matches[condition]) // i don't no how exactly
$result = $matches[true-condition];
else
$result = $matches[false-condition]
所以如果$registry['total_found'] = 100; 最终结果将是«职业是演员。已找到 100 个职位空缺。您所在城市的演员»。
如果$registry['total_found'] = 0; 最终结果将是«职业是演员。未找到职位空缺。你所在城市的演员»。
【问题讨论】:
-
你能提供
$registry的样本吗?{total_found}到底是什么?字符串中的条件,布尔值? -
$registy = array( 'profession_name' => 'actor', 'total_found' => 100, ); -
我计划在我的函数中检查值或条件,无论它是真还是假,是否为空,可能等于或不等于。
-
好的,但是在您的示例中,
'total_found' => 100、100与什么比较? -
如果在我的回调中我可以确定 $matches[4] 是我的条件值,我会检查它是否为空,并将真假模式解析为结果文本,我会很高兴。跨度>
标签: php regex preg-replace preg-match pcre