我如何连接函数的输出


How can I concatenate functions output?

任务如下:

Nel mezzo del cammin 
di nostra vita
从这个:

  nel-MEZzo---del-cammin, <strong>BRAKELINE</strong>di nostra-vita. 

我真的很讨厌这个语法:

function custom_function($v){
return str_replace("BRAKELINE","'n",$v);
}
$SRC = '  nel-MEZzo---del-cammin, <strong>BRAKELINE</strong>di nostra-vita. ';
$v = ucfirst(trim(strtolower(custom_function(preg_replace('/[^'w]+/',"'040",strip_tags($SRC))))));
echo $v;

和我尝试了一些新的东西:

function ifuncs($argv=NULL,$funcs=array()){
 foreach($funcs as $func){
    $argv = $func($argv);
 }
 return $argv;
}
$SRC = '  nel-MEZzo---del-cammin, <strong>BRAKELINE</strong>di nostra-vita. ';
$v = ifuncs(
$SRC,
array(
    'strip_tags',
    'f1' => function($v){ return preg_replace('/[^'w]+/',"'040",$v); },
    'f2' => function($v){
        return str_replace("BRAKELINE","'n",$v);
    },
    'strtolower',
    'trim',
    'ucfirst'
)
);
echo $v;

它工作得很好,但我想知道是否有更好的方法(即现有的库)来做到这一点

您所写的是array_reduce()的工作原理:

$fns = array(
    'strip_tags',
    function($v) {
        return preg_replace('/[^'w]+/', ' ', $v);
    },
    function($v) {
        return str_replace('BRAKELINE', "'n", $v);
    },
    'strtolower',
    'trim',
    'ucfirst',
);
$input = '  nel-MEZzo---del-cammin, <strong>BRAKELINE</strong>di nostra-vita. ';
$v = array_reduce($fns, function($result, $fn) {
  return $fn($result);
}, $input));

应用于当前功能:

function ifuncs(array $funcs, $input = null) 
{
    return array_reduce($funcs, function($result, $fn) {
        return $fn($result);
    }, $input));
}

不短,但相当优雅。

function fns($input=NULL,$fns=array()){
   $input = array_reduce($fns, function($result, $fn) {
     return $fn($result);
   }, $input);
   return $input;
}