我正面临一个问题,从html代码调用PHP函数,并填写函数的参数。然后输出HTML代码和函数的返回值。
为例:
在PHP文件的某个地方定义函数
function html_field($type,$name,$value){
//some code here
return $out;
}
// or other example function
function boldme($text){
return "<b>$text</b>";
}
之后生成html输出字符串与php函数里面(如标签)
HTML字符串:
$html = "<h1><label for="foo">{call~html_field("text","name","value")} </label><input type="text" name="foo" id="foo" /> </h1>"
或
$html = "<h1><label for="foo">{call~boldme("text")} </label><input type="text" name="foo" id="foo" /> </h1>"
解决方案应该像这样结束:
$html = "<h1><label for="foo"><input type="text" name="name" ...> </label><input type="text" name="foo" id="foo" /> </h1>"
或
$html = "<h1><label for="foo"><b>text</b> </label><input type="text" name="foo" id="foo" /> </h1>"
需要过滤这个字符串…
注意:包含从模板和主题中收集的html数据的字符串;它们是不可知的文件,里面有纯HTML。 我使用preg_replace_callback
来创建所需的功能,但现在都消失了,感谢我的老板....@ # !
如果需要解析字符串并在此基础上调用某些函数,可以使用preg_replace_callback
函数。
像这样的代码应该可以达到这个效果:
$html = "<p>{functionName('value1', 'value2')}</p>";
function contentParser($matches)
{
$function = $matches[1];
$parameters = array_slice($matches, 2);
return call_user_func_array($function, $parameters);
}
function functionName($valueA, $valueB)
{
return "You called functionName with values " . $valueA . " and " . $valueB;
}
echo preg_replace_callback(
"/'{('w+)'(['"']([^'"']+)['"'](?:, ?['"']([^'"']+)['"'])?')'}/",
"contentParser",
$html);
这将打印以下内容:
You called functionName with values value1 and value2
注意,我的正则表达式有一个大问题。
你可以把这些值(在你的html中)用单引号或双引号("或')括起来,你也可以把它们混在一起…这导致了第二个问题,你不能在你的值中使用这两个(我不检查转义序列)。
一个更简单的模式,只使用一个字符作为值包装器(当然,您可以更改该字符):
"/'{('w+)'(#([^#]+)#(?:, ?#([^#]+)#)?')'}/"
这里我使用锐利(#)作为值分隔符,那么,你的html必须看起来像这样:
<p>{functionName(#value1#, #value2#)}</p>
$html
字符串从哪里来?如果是静态代码,使用标准php:
$html = '<h1><label for="foo">' . html_field("text","name","value") . '</label><input type="text" name="foo" id="foo" /> </h1>';
如果它们是从数据库或文件或其他地方加载的,你必须选择:
- 制作自己的模板引擎,工作量大,bug少,浪费时间
- 使用轻量级的模板引擎,如twig和定义你的函数过滤器