Reputation: 326
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.
Upvotes: 1
Views: 56
Reputation: 173662
What you have written is how array_reduce()
works:
$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));
}
Upvotes: 3
Reputation: 326
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;
}
Upvotes: 0