doufei6456 2013-01-12 14:25
浏览 27
已采纳

通过几个函数运行变量

I am attempting to run a variable through several functions to obtain a desired outcome.

For example, the function to slugify a text works like this:

        // 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);

However, we can see that there is a pattern in this example. The $text variable is passed through 5 function calls like this: preg_replace(..., $text) -> trim($text, ...) -> iconv(..., $text) -> strtolower($text) -> preg_replace(..., $text).

Is there a better way we can write the code to allow a variable sieve through several functions?

One way is to write the above code like this:

$text = preg_replace('~[^-\w]+~', '', strtolower(iconv('utf-8', 'us-ascii//TRANSLIT', trim(preg_replace('~[^\\pL\d]+~u', '-', $text), '-'))));

... but this way of writing is a joke and mockery. It hinders code readability.

  • 写回答

2条回答 默认 最新

  • doudang1052 2013-01-12 14:35
    关注

    Since your "function pipeline" is fixed then this is the best (and not coincidentally simplest) way.

    If the pipeline were to be dynamically constructed then you could do something like:

    // 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 socket通信实现多人聊天室疑惑
  • ¥15 DEV-C++编译缺失
  • ¥33 找熟练码农写段Pyhthon程序
  • ¥100 怎么让数据库字段自动更新
  • ¥15 antv g6 力导向图布局
  • ¥15 quartz框架,No record found for selection of Trigger with key
  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数