Alexander Alexander - 5 months ago 23
PHP Question

PHP preg_match for empty lines

I want to have an array of strings with

<answers>
and
<names>
tags from my xml file, (it's not guaranteed for file to be valid, so I can't parse it with simplexml)

after code execution I get an array with
array[0]
equal to something empty with lenght of 5, I thought that my regexp
/^[\s\S]*$/
should remove all empty characters and lines, but on practice that
array[0]
element is stays the same as after array_filter.

how can I get this array without emty values?

array(8) {
[0]=>
string(5) " "
[3]=>
string(39) "<name>первый вопрос</name> "
[4]=>
string(68) "<answer id="1">Первый ответ на вопрос 1</answer> "
[5]=>
string(68) "<answer id="2">Второй ответ на вопрос 1</answer> "
[6]=>
string(68) "<answer id="3">Третий ответ на вопрос 1</answer> "
[9]=>
string(51) "<name> второй вопрос</name> "
[10]=>
string(68) "<answer id="1">Первый ответ на вопрос 2</answer> "
[11]=>
string(68) "<answer id="2">Второй ответ на вопрос 2</answer> "
}


I have xml file

<?xml version="1.0" standalone="yes"?>
<test>
<question id="1">
<name>первый вопрос</name>
<answer id="1">Первый ответ на вопрос 1</answer>
<answer id="2">Второй ответ на вопрос 1</answer>
<answer id="3">Третий ответ на вопрос 1</answer>
</question>
<question id="2">

<name> второй вопрос</name>
<answer id="1">Первый ответ на вопрос 2</answer>
<answer id="2">Второй ответ на вопрос 2</answer>
</question>
</test>


and code

<?php
$xml = file_get_contents("test.xml");
$per = preg_replace('/<question[\s\S]+?>|<\/question>|<test>|
<\/test>|<\?xml[\s\S]+?>/i', "", $xml);
$array = explode("\n", $per);
function filter($str)
{
return !preg_match('/^[\s]*$/', $str);
}

$array = array_filter($array, "filter");
var_dump ($array);
?>

Answer

Simple one liner.

$array = array_filter(array_map('trim', file('example.xml')), 'strlen');

However, why do you use regular expressions to parse XML documents? I recommend you using native DOMDocument or SimpleXMLElement instead.

Example of DOMDocument:

$dom = new DOMDocument;
$dom->loadXMLFile('example.xml');
$xpath = new DOMXPath($dom);
$q2a1 = $xpath->evaluate('string(/question[@id="2"]/answer[@id="1"])');

Example of SimpleXMLElement:

$xml = new SimpleXMLElement('example.xml', 0, true);
$q2a1 = (string)$xml->xpath('/question[@id="2"]/answer[@id="1"]')->item(0);
Comments