php foreach preg_match' d line,get next lines

时间:2016-11-22 08:25:02

标签: php foreach preg-match-all

我希望标题是自我解释的。

我想逐行遍历xml文件,然后匹配一条特定的行(从该行获取属性),然后在该行之后获取下一行X行。

我有以下代码,试图这样做,但我似乎无法弄清楚如何获得下一个X行。

$file = 'Electric.xml';
$lines = file($file);//file in to an array

foreach($lines as $line){

    $reads = element_attributes('WINDOW',$line);

    if($reads['class'] == 'Bracelets'){
        print_r($reads);
    }

    if($reads['class'] == 'Handbags'){
        print_r($reads);
    }
}

function element_attributes($element_name, $xml) {
    if ($xml == false) {
        return false;
    }
    // Grab the string of attributes inside an element tag.
    $found = preg_match('#<'.$element_name.
            '\s+([^>]+(?:"|\'))\s?/?>#',
            $xml, $matches);
    if ($found == 1) {
        $attribute_array = array();
        $attribute_string = $matches[1];
        // Match attribute-name attribute-value pairs.
        $found = preg_match_all(
                '#([^\s=]+)\s*=\s*(\'[^<\']*\'|"[^<"]*")#',
                $attribute_string, $matches, PREG_SET_ORDER);
        if ($found != 0) {
            // Create an associative array that matches attribute
            // names to attribute values.
            foreach ($matches as $attribute) {
                $attribute_array[$attribute[1]] =
                        substr($attribute[2], 1, -1);
            }
            return $attribute_array;
        }
    }
    // Attributes either weren't found, or couldn't be extracted
    // by the regular expression.
    return false;
}

2 个答案:

答案 0 :(得分:0)

使用适当的解析器like SimpleXML来解析文件。那你的问题就变得微不足道了。 PHP manual contains a tutorial可帮助您入门。

在这种情况下,您只需遍历这些行,检查您要查找的标记的属性,直到找到匹配项。然后,遍历下一个#元素,将它们保存到数组中 像这样:

$xml = new SimpleXML ("file.xml");
foreach ($xml->node->element as $element) {
    if ($element->attribute != "match") {
         continue;
    }

    // If we get here we want to save the next # lines/elements.
}

答案 1 :(得分:0)

$linesLength = count($lines);
$XLines = array();
for($index = 0; $index < $linesLength; $index++){

    $reads = element_attributes('WINDOW',$line);

    if($reads['class'] == 'Bracelets'){
        print_r($reads);
        $XLines[] = array_slice($array, $index, $X);
        $index += $X;
    }

    if($reads['class'] == 'Handbags'){
        print_r($reads);
        $XLines[] = array_slice($array, $index, $X);
        $index += $X;
    }
}