PHP语法糖:如何在给定输入上多次应用函数?
从数据库中,我得到一个文本,其中函数PHP语法糖:如何在给定输入上多次应用函数?,php,function,syntax,syntactic-sugar,Php,Function,Syntax,Syntactic Sugar,从数据库中,我得到一个文本,其中函数htmlentities()应用了四次。示例文本: 特色菜及;amp;amp;车间 为了解码此文本,我必须执行以下操作: $out = html_entity_decode(html_entity_decode(html_entity_decode(html_entity_decode("specials & workshops")))); 结果: 专题讲座及工作坊 PHP中是否有一种自然的方法可以更高效地编写此文件?
htmlentities()
应用了四次。示例文本:
特色菜及;amp;amp;车间
为了解码此文本,我必须执行以下操作:
$out = html_entity_decode(html_entity_decode(html_entity_decode(html_entity_decode("specials & workshops"))));
结果:
专题讲座及工作坊
PHP中是否有一种自然的方法可以更高效地编写此文件?为什么不声明一个函数来实现此目的
$in = "specials & workshops";
$decode = function($in) {
foreach(range(1,4) as $x) $in = html_entity_decode($in); return $in; };
function decode($in) {
foreach(range(1,4) as $x)
$in = html_entity_decode($in);
return $in;
}
// inline
$out = $decode($in);
// traditional
$out = decode($in);
根据@JayBlanchard的递归思想,我没有创建以下内容-非常喜欢它:
/**
* Apply a function to a certain input multiple times.
*
* @param $input: The input variable:
* @param callable $func: The function to call.
* @param int $times: How often the function should be called. -1 for deep call (unknown number of calls required). CAUTION: If output always changes this results in an endless loop.
* @return mixed
*/
function recapply($input,callable $func,int $times) {
if($times > 1) {
return recapply($func($input),$func,$times - 1);
} else if($times == -1) {
$res = $func($input);
if($res === $input) {
return $input;
} else {
return recapply($res,$func,-1);
}
}
return $func($input);
}
工作示例调用:
echo recapply("specials & workshops","html_entity_decode",4);
我喜欢以一种递归的方式来做,这样我就不需要知道要匹配多少个实体
$string = 'specials & workshops';
$entity = '/&/';
function recurseHTMLDecode($str, $entity) {
preg_match($entity, $str, $matches);
echo count($matches);
if(1 == count($matches)) {
$str = html_entity_decode($str);
$str = recurseHTMLDecode($str, $entity);
return $str;
} else {
return $str;
}
}
var_dump(recurseHTMLDecode($string, $entity));
这将返回:
11110字符串(20)“特价商品和研讨会”
这是你的电话号码
这可以通过向函数中添加一个实体白名单来改进,这样在调用时就不必指定实体,只需在白名单中循环即可。这将解决字符串中包含多个实体的问题。这可能相当复杂。你必须递归地做。我想说,这只是你的偏好。但是请保持简单,并为此创建一个函数。谢谢您的回答。我认为创建一个函数是必要的。但是如果你不知道使用的次数呢?@JayBlanchard:为了更广泛的适用性,我还扩展了我的方法。然而,无止境递归只适用于一个函数,该函数在一段时间后总是得到相同的结果,否则它会导致无止境循环。这是针对特定问题的良好解决方案!