简体   繁体   English

如何连接函数输出?

[英]How can I concatenate functions output?

The task is obtain this: 任务是获得这个:

Nel mezzo del cammin 
di nostra vita

from this: 由此:

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

I'm really sick about this syntax: 我真的厌倦了这种语法:

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;

and I tried something new: 我尝试了一些新的东西:

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;

It's works very well, but I would to know if there is a better way (aka existing library) to do this. 它运行得很好,但我想知道是否有更好的方法(也就是现有的库)来做到这一点。

What you have written is how array_reduce() works: 你写的是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));

Applied to your current function: 适用于您当前的功能:

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

No shorter, but quite more elegant. 不短,但更优雅。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM