This is interesting. What about this solution?
function pipe($v, $fs)
{
foreach(explode('|', $fs) as $f)
{
if(strpos($f, '[') === FALSE){
$v = call_user_func($f, $v);
}else{
list($fun, $args) = explode('[', trim($f), 2);
$args = explode(',', str_replace('!', $v, substr($args, 0, -1)));
$v = call_user_func_array($fun, $args);
}
}
return $v;
}
echo pipe(' test STRING??', 'trim|strtolower|str_repeat[!,3]|str_replace[string,cheese,!]');
This prints out
test cheese??test cheese??test cheese??
The function pipe takes two arguments. The first is the initial value and the second is a pipe-delimited list of functions to which to apply to the first argument. To allow for multi-argument functions, the [ and ] characters can be used (like parentheses are used in PHP). The placeholder '!' can be used to specify where to insert the strings along the chain.
In the above example, the following happens:
trim(' test STRING??') => 'test STRING??'
strtolower('test STRING??') => 'test string??'
str_repeat('test string??', 3) => 'test string??test string??test string??'
str_replace('string', 'cheese', 'test string??test string??test string??') => 'test cheese??test cheese??test cheese??'
The characters [, ], and ! were chosen arbitrarily. Also, this doesn't allow you to use commas in the function arguments, although it could be expanded to allow this.
Interesting question!
(Idea for '|' delimited list of functions taken from Code Igniter, although they don't do variable replacement. It could also easily be a string array, but the array() constructor is verbose)