字符串反转并转换大小写其中用到了闭包还省去了foreach

看到朋友的代码感觉不错摘录下来做下笔记

  function reversalString($inputString="Auuuub iiii ppppp")
    {
        defined('UPPER') or define('UPPER', 1);  //大写标识符
        defined('LOWER') or define('LOWER', 2);  //小写标识符

        $newStringList = [];
        $inputStringList = explode(' ',$inputString);
       // var_dump($inputStringList);
        foreach ($inputStringList as $inputStringInfo) {
            $indexList = str_split($inputStringInfo);
           // var_dump($indexList);
            array_walk($indexList,function(&$world){
                $world = strtoupper($world) == $world ? UPPER : LOWER;
               // echo $world;
            });
            //var_dump( $indexList);
            $reversalStringList = str_split(strrev($inputStringInfo));

            array_walk($reversalStringList,function (&$reversalInfo,$key) use($indexList) {
                if (isset($indexList[$key])) {
                    //echo  $indexList[$key];
                    $reversalInfo = $indexList[$key] == UPPER ? strtoupper($reversalInfo) :strtolower($reversalInfo);
                }
            });

            $newStringList[] = implode('',$reversalStringList);
        }

        $newString = implode(' ',$newStringList);

        return $newString;
    }
echo  reversalString(); exit;

猜你喜欢

转载自blog.csdn.net/Lucky____Boy/article/details/86688372
今日推荐