dsdeeaquu38538545 2013-12-02 10:55 采纳率: 100%
浏览 7
已采纳

递归标记器[关闭]

I am trying to create a recursive tokenizer that would handle this string and convert it into a multidimensional array.

Input:

a,b,c(a,b,c),d(a,b(a,b)),e

Output

$r = [
    'a' => 'a',
    'b' => 'b',
    'c' => [
        'a' => 'a',
        'b' => 'b',
        'c' => 'c'
        ],
    'd' => [
        'a' => 'a',
        'b' => [
            'a',
            'b'
            ]
        ],
    'e' => 'e'
    ];

Any ideas?

  • 写回答

1条回答 默认 最新

  • duanmu2015 2013-12-02 12:01
    关注

    I would tokenize your string first and then convert it into a JSON string and decode that one to an associative array. I build a little function to do that:

    $str = 'a,b,c(a,b,c),d(a,b(a,b)),e';
    
    function parse($str) {
        preg_match_all('/[a-z\\(\\)]/', $str, $matches);
    
        $jsonStr = '{';
        $tokensCount = count($matches[0]);
        $tokens = $matches[0];
    
        for($i = 0; $i < $tokensCount; ++$i) {
            $nextToken = isset($tokens[$i+1])?trim($tokens[$i+1]):false;
            $currentToken = trim($tokens[$i]);
    
            if($currentToken == '(') {
                $jsonStr .= '{';
                continue;
            } elseif( $currentToken == ')') {
                $jsonStr = substr($jsonStr, 0, -2) . '}, ';
                continue;
            }
    
            if($nextToken == '(') {
                $jsonStr .= '"' . $currentToken . '": ';
            } else {
                $jsonStr .= '"' . $currentToken . '": "' . $currentToken . '", ';
            }
        }
    
        $jsonStr = substr($jsonStr, 0, -2) . '}';
    
        return json_decode($jsonStr, true);
    }
    
    var_dump(parse($str));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?