草庐IT

php - 解析类似 JSON 的标记

coder 2024-01-05 原文

老实说,我不知道这是什么标记(我想知道这个标记是否有名称)。解析这样的结构最简单的方法是什么?我在 txt 文件中有很多。

unlockType BirthdayCake {
       // Don't delete
    commonName      "Birthday Cake"
    autoTag
    category        Item
    path            models/
    timedExclusive  1
    descSymbol      BirthdayCakeDesc
    dispSymbol      BirthdayCakeDisp
    flairCfg        "Cake/Idle.aaf mat_BirthdayCake< /scale 1.5 /animation Cake/Idle.aaf 0 looping 0.8  /followDist 3.0 /moveSlew 0.0666  /moveVelThresh 10.0 /animEaseTime 1.0 /zOffRobot 2.7 /rotX 20.0 /zSpinDef bone_spinA 80.0"
    //OnInspectOrUnlock Menus previewInit Cake/Idle.aaf BirthdayCake< /scale 1.5 /animation Cake/Idle.aaf 0 looping 0.8 /rotSpeed 30 /pos 3.5 0 1 /scaleMult 1.0
    property        BirthdaySpirit          10
}

最佳答案

$str = "unlockType BirthdayCake {
       // Don't delete
    commonName      \"Birthday Cake\"
    autoTag
    category        Item
    path            models/
    timedExclusive  1
    descSymbol      BirthdayCakeDesc
    dispSymbol      BirthdayCakeDisp
    flairCfg        \"Cake/Idle.aaf mat_BirthdayCake< /scale 1.5 /animation Cake/Idle.aaf 0 looping 0.8  /followDist 3.0 /moveSlew 0.0666  /moveVelThresh 10.0 /animEaseTime 1.0 /zOffRobot 2.7 /rotX 20.0 /zSpinDef bone_spinA 80.0\"
    //OnInspectOrUnlock Menus previewInit Cake/Idle.aaf BirthdayCake< /scale 1.5 /animation Cake/Idle.aaf 0 looping 0.8 /rotSpeed 30 /pos 3.5 0 1 /scaleMult 1.0
    property        BirthdaySpirit          10
}

unlockType PetFish3 {
        commonName              \"Lionfish\"
        autoTag
        category                Pet
        path                    flair/
        descSymbol              PetFish3Desc
        dispSymbol              PetFish3Disp
        flairCfg                \"pet flair/PetFishes/PetFish3.amf mat_PetFishes< /scale 1.1 /animation flair/PetFishes/idle3.aaf 0 looping 0.45 /moveAnim flair/PetFishes/fly1.aaf 1 looping 1.62  /followDist 3.0 /moveSlew 0.045 /moveVelThresh 8.0 /animEaseTime 0.45 /zOffRobot 2.6 /rotX 15.0 /moveSlew 0.05 /turnToMove 230\"
}
";

function parseThis($text)
{
    $types = array();
    preg_match_all('#(unlockType [^\{]+{.+?\n\s*})#s',$text,$matches);
    foreach($matches[1] as $str)
    {
        $typeName = preg_replace('#^[^ ]+ ([^ ]+).*#s','$1',$str);
        $contents = preg_split('#(\r?\n)+#',$str);
        $contents = array_map('trim',$contents);
        array_pop($contents);
        array_shift($contents);
        $data = array();
        foreach($contents as $line)
        {
            if(substr($line,0,2)=='//') continue;
            $parts = preg_split("#(\t+|\s{3,})#",$line);
            $title = array_shift($parts);
            $partC = count($parts);
            $data[$title] = $partC==1 ? $parts[0] : ($partC==0 ? '' : $parts);
        }
        $types[$typeName] = $data;
    }
    return $types;
}
$types = parseThis($str);
echo '<pre>'.print_r($types,true).'</pre>';

输出:

Array
(
    [BirthdayCake] => Array
        (
            [commonName] => "Birthday Cake"
            [autoTag] => 
            [category] => Item
            [path] => models/
            [timedExclusive] => 1
            [descSymbol] => BirthdayCakeDesc
            [dispSymbol] => BirthdayCakeDisp
            [flairCfg] => "Cake/Idle.aaf mat_BirthdayCake< /scale 1.5 /animation Cake/Idle.aaf 0 looping 0.8  /followDist 3.0 /moveSlew 0.0666  /moveVelThresh 10.0 /animEaseTime 1.0 /zOffRobot 2.7 /rotX 20.0 /zSpinDef bone_spinA 80.0"
            [property] => Array
                (
                    [0] => BirthdaySpirit
                    [1] => 10
                )

        )

    [PetFish3] => Array
        (
            [commonName] => "Lionfish"
            [autoTag] => 
            [category] => Pet
            [path] => flair/
            [descSymbol] => PetFish3Desc
            [dispSymbol] => PetFish3Disp
            [flairCfg] => "pet flair/PetFishes/PetFish3.amf mat_PetFishes< /scale 1.1 /animation flair/PetFishes/idle3.aaf 0 looping 0.45 /moveAnim flair/PetFishes/fly1.aaf 1 looping 1.62  /followDist 3.0 /moveSlew 0.045 /moveVelThresh 8.0 /animEaseTime 0.45 /zOffRobot 2.6 /rotX 15.0 /moveSlew 0.05 /turnToMove 230"
        )

)

粗略的解释

  • 使用preg_match_all 找到每个 block (unlockType someRandomText { .... })
  • 遍历 preg_match_all 的每个结果(每个 block )以单独解析 block
    • 用换行符拆分 {..} 的内容,然后将每个结果映射到 trim() 以删除任何前导和尾随空格/制表符
      • 用 3 个或更多空格分隔每一行(因为似乎没有使用适当的制表符)
      • 使用拆分的第一个结果作为我们数组的键,然后将拆分的其余部分压入值

关于php - 解析类似 JSON 的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18084534/

有关php - 解析类似 JSON 的标记的更多相关文章

  1. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby - 用逗号、双引号和编码解析 csv - 2

    我正在使用ruby​​1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\

  4. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  5. ruby-on-rails - 我更新了 ruby​​ gems,现在到处都收到解析树错误和弃用警告! - 2

    简而言之错误:NOTE:Gem::SourceIndex#add_specisdeprecated,useSpecification.add_spec.Itwillberemovedonorafter2011-11-01.Gem::SourceIndex#add_speccalledfrom/opt/local/lib/ruby/site_ruby/1.8/rubygems/source_index.rb:91./opt/local/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/rails/gem_dependency.rb:275:in`==':und

  6. ruby-on-rails - 如何使用 Rack 接收 JSON 对象 - 2

    我有一个非常简单的RubyRack服务器,例如:app=Proc.newdo|env|req=Rack::Request.new(env).paramspreq.inspect[200,{'Content-Type'=>'text/plain'},['Somebody']]endRack::Handler::Thin.run(app,:Port=>4001,:threaded=>true)每当我使用JSON对象向服务器发送POSTHTTP请求时:{"session":{"accountId":String,"callId":String,"from":Object,"headers":

  7. ruby - 用 YAML.load 解析 json 安全吗? - 2

    我正在使用ruby2.1.0我有一个json文件。例如:test.json{"item":[{"apple":1},{"banana":2}]}用YAML.load加载这个文件安全吗?YAML.load(File.read('test.json'))我正在尝试加载一个json或yaml格式的文件。 最佳答案 YAML可以加载JSONYAML.load('{"something":"test","other":4}')=>{"something"=>"test","other"=>4}JSON将无法加载YAML。JSON.load("

  8. ruby - Ruby 是否有类似于 Perl 的 "perl -d"的逐步调试器? - 2

    Ruby是否有逐步调试器,类似于Perl的“perl-d”? 最佳答案 ruby-debug(对于ruby1.8),debugger(对于ruby1.9),byebug(对于ruby​​2.0)以及trepanning系列都有一个-x或--trace选项。在调试器内部,命令setlinetrace将打开或关闭线路跟踪。这是themanualforruby-debug原来的答案已经修改,因为数据噪声文章的链接,唉,不再有效了。还添加了ruby​​-debug的后继者 关于ruby-Ruby

  9. ruby - 使对象的行为类似于 ruby​​ 中并行分配的数组 - 2

    假设您在Ruby中执行此操作:ar=[1,2]x,y=ar然后,x==1和y==2。是否有一种方法可以在我自己的类中定义,从而产生相同的效果?例如rb=AllYourCode.newx,y=rb到目前为止,对于这样的赋值,我所能做的就是使x==rb和y=nil。Python有这样一个特性:>>>classFoo:...def__iter__(self):...returniter([1,2])...>>>x,y=Foo()>>>x1>>>y2 最佳答案 是的。定义#to_ary。这将使您的对象被视为要分配的数组。irb>o=Obje

  10. ruby - 如何使用 Nokogiri 解析纯 HTML 表格? - 2

    我想用Nokogiri解析HTML页面。页面的一部分有一个表,它没有使用任何特定的ID。是否可以提取如下内容:Today,3,455,34Today,1,1300,3664Today,10,100000,3444,Yesterday,3454,5656,3Yesterday,3545,1000,10Yesterday,3411,36223,15来自这个HTML:TodayYesterdayQntySizeLengthLengthSizeQnty345534345456563113003664354510001010100000344434113622315

随机推荐