简体   繁体   English

需要帮助解析PHP中的一些数据

[英]Need help parsing some data in PHP

I need to be able to parse this sort of data in PHP: 我需要能够在PHP中解析此类数据:

 Acct: 1 
 email       : bleh@gmail.com 
 status      : online 
 -------------------------------------------------- 

 Acct: 2 
 email       : dfgg@fgfg.com     
 status      : banned 
 -------------------------------------------------- 

 Acct: 3 
 signedupname  : SomeUsername     
 somethingelse  : offline 
 -------------------------------------------------- 

As you can see the data is largely random. 如您所见,数据在很大程度上是随机的。 The only thing that remains the same is the ----- seperating each entry and the Acct: 1 bits. 唯一保持不变的地方是-----分隔每个条目和Acct: 1位。 The padding between each : often changes as does the variable to represent each bit of data. 每个:之间的填充通常会随着代表每个数据位的变量而变化。

I've tried going through and parsing it all myself using regex but I am defenately not skilled enough to be able to do it properly. 我已经尝试过使用正则表达式自己解析所有内容,但是我绝对不够熟练,无法正确执行它。 At the end of this I want data according to the following: 最后,我要根据以下数据:

Acct: <integer>
var1: <string>
var2: <string>

If that makes any sense at all. 如果有任何意义的话。 It doesn't need to be that effeciant, as I will need to do this about once a day and I do not mind waiting for how-ever long it needs. 它不需要那么高效,因为我每天大约需要做一次,而且我不介意等待它需要多长时间。

Thank you. 谢谢。 :) :)

Edit: This is what I did on my own: 编辑:这是我自己做的:

<?php

$data = file_get_contents('records.txt');
$data = explode('******** Saved Host list with acct/variables ********', $data);
$data = explode('--------------------------------------------------', $data[1]);

foreach($data as &$dataz)
{
    $dataz = trim($dataz);
}

$data = str_replace('Acct:', "\nAcct:", $data);

foreach($data as $dataz)
{
    preg_match('/Acct: (.*)/', $dataz, $match);
    $acct = $match[1];
    preg_match('/: (.*)/', $dataz, $match);
    $var1 = $match[1];
    echo $var1;
}

?>

I got as far as extracting the Acct: part, but anything beyond that I simply can't get my head around. Acct:提取了Acct:部分,但除此之外,我Acct:至无法理解。

This piece of code will take your entire input and produce an associative array for each record in your input: 这段代码将吸收您的整个输入,并为输入中的每个记录生成一个关联数组:

// replace ----- with actual number of dashes
foreach (explode('-----', $input) as $entry) {
  $entry = trim($entry);
  $record = array();
  foreach (explode("\n", $entry) as $line) {
    $parts = explode(':', $line);
    $varname = trim($parts[0]);
    $value = trim($parts[1]);
    $record[$varname] = $value;
  }
  // Do anything you want with $record here
}

Edit: I just had a look at the code you posted. 编辑:我只是看看您发布的代码。 You really don't need regular expressions for what you're trying to do. 您确实不需要正则表达式来执行您想做的事情。 Regex can be really handy when used in the right place, but most of the time, it's not the right thing to use. 在正确的位置使用正则表达式会非常方便,但是在大多数情况下,使用它不是正确的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM