从HTML字符串调用php函数

时间:2013-04-24 11:27:24

标签: php

我遇到了从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>"

OR

$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>"

OR

$html = "<h1><label for="foo"><b>text</b> </label><input type="text" name="foo" id="foo" /> </h1>"

需要过滤此字符串...

注意: 包含模板和主题中收集的html数据的字符串, 它们是纯HTML内部的不可知文件。

我使用preg_replace_callback来创建所需的功能,但现在一切都消失了,多亏了我的老板......!@#!

2 个答案:

答案 0 :(得分:1)

$html字符串来自何处?如果是静态代码,请使用标准的php:

$html = '<h1><label for="foo">' . html_field("text","name","value") . '</label><input type="text" name="foo" id="foo" /> </h1>';

如果从数据库或文件或其他任何地方加载它们,您必须选择:

  • 制作自己的模板引擎,工作量大,漏洞少,浪费时间
  • 使用像twig这样的轻量级模板引擎,并将您的功能定义为filters

答案 1 :(得分:1)

如果你需要解析一个字符串并根据它调用一些函数,你可以使用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+)\(#([^#]+)#(?:, ?#([^#]+)#)?\)\}/"

这里我使用sharp(#)作为值分隔符,然后,你的html必须如下所示:

<p>{functionName(#value1#, #value2#)}</p>