【问题标题】:How can I read and parse the contents of this text file?如何读取和解析此文本文件的内容?
【发布时间】:2012-09-11 13:13:44
【问题描述】:

我想像 C++ 那样读取文本文件

这是文本文件中的示例

(item(name 256) (desc 520)(Index 1)(Image "Wea001") (specialty  (aspeed 700)))
(item   (name 257)  (desc 520)           (Index 2)  (Image "Wea002")(specialty(Attack 16 24)))

我想要这样的输出

name : 256
Desc : 520
Index : 1
Image : Wea001
Specialty > aspeed : 700

Name : 257
Desc : 520
Index : 2
Image : Wea002
Speciality > Attack : 16 24

这可能吗?

我试过了:

preg_match_all('/name\s+(.*?)\)\+\(desc\s+(.*?)\)\+\(Index\s+(.*?)\)/', $text, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
  list (, $name, $desc, $index) = $match;
    echo 'name : '.$name.' <br> Desc : '.$desc.'<br> Index : '.$index.'';
  }

但它没有给我想要的正确输出。

谢谢

【问题讨论】:

  • 天哪,这是一种令人讨厌的格式。它来自哪里?能改吗?
  • Lisp 攻击!这么多括号!

标签: php


【解决方案1】:
<?php
    $txt = '(item(name 256) (desc 520)(Index 1)(Image "Wea001") (specialty  (aspeed 700))(item   (name 257)  (desc 520)           (Index 2)  (Image "Wea002")(specialty(Attack 16 24)))';

    preg_match_all('/name\s+(?P<name>\w+).*desc\s+(?P<desc>\d+).*Index\s+(?P<index>\d+).*Image\s+(?P<img>.*)\).*specialty\s*\((?P<speciality>.*)\)\)\)/', $txt, $matches);
  foreach($matches['name'] AS $id => $name){
       echo 'name : '.$name.' <br> Desc : '.$matches['desc'][$id].'<br> Index : '.$matches['index'][$id].'<br> speciality : '.$matches['speciality'][$id].'';
}

假设你总是有相似的数据格式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2019-06-10
    相关资源
    最近更新 更多