php - 通过多个函数运行一个变量

标签 php function variables

我正在尝试通过多个函数运行变量以获得所需的结果。

例如,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/

相关文章:

android - 如何通过单击和更改按钮功能在另一个布局中加载布局?

php - 显示单页 Code Igniter MVC 的多个 View

java - 在类中运行具有静态变量的相同 java 程序两次

php - 将编号行/序列号添加到数据库查询结果集中

javascript - 如何在选择而不是更改的下拉菜单中调用 JavaScript 函数

c++ - C++中的函数帮助

javascript - 带条件声明变量

php - 多删除,一张表为空时出现未知表错误

php - 值在数组中的 MySQL SELECT 语句

function - 关于lua for循环