我正在尝试通过多个函数运行变量以获得所需的结果。
例如,function to slugify a text工作原理如下:
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
// trim
$text = trim($text, '-');
// transliterate
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
// lowercase
$text = strtolower($text);
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
但是,我们可以看到这个例子中有一个模式。 $text
变量通过 5 个函数调用传递,如下所示:preg_replace(..., $text) -> trim($text, ...) -> iconv(... , $text) -> strtolower($text) -> preg_replace(..., $text)
。
是否有更好的方法可以编写代码以允许变量筛选通过多个函数?
一种方法是像这样编写上面的代码:
$text = preg_replace('~[^-\w]+~', '', strtolower(iconv('utf-8', 'us-ascii//TRANSLIT', trim(preg_replace('~[^\\pL\d]+~u', '-', $text), '-'))));
...但是这样的写法是一种笑话和 mock 。它阻碍了代码的可读性。
最佳答案
既然你的“函数管道”是固定的,那么这是最好的(而且并非巧合的是最简单的)方法。
如果要动态构建管道,那么您可以执行以下操作:
// construct the pipeline
$valuePlaceholder = new stdClass;
$pipeline = array(
// each stage of the pipeline is described by an array
// where the first element is a callable and the second an array
// of arguments to pass to that callable
array('preg_replace', array('~[^\\pL\d]+~u', '-', $valuePlaceholder)),
array('trim', array($valuePlaceholder, '-')),
array('iconv', array('utf-8', 'us-ascii//TRANSLIT', $valuePlaceholder)),
// etc etc
);
// process it
$value = $text;
foreach ($pipeline as $stage) {
list($callable, $parameters) = $stage;
foreach ($parameters as &$parameter) {
if ($parameter === $valuePlaceholder) {
$parameter = $value;
}
}
$value = call_user_func_array($callable, $parameters);
}
// final result
echo $value;
<强> See it in action 。
关于php - 通过多个函数运行一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14294238/