我想从我的xml文件中有一个带有<answers>
和<names>
标签的字符串数组,(不能保证文件有效,所以我不能用simplexml解析它)
代码执行后,我得到一个数组,array[0]
等于长度为 5 的空值,我认为我的正则表达式/^[sS]*$/
应该删除所有空字符和行,但在实践中array[0]
元素保持不变array_filter之后。
如何在没有 emty 值的情况下获取此数组?
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> "
}
我有 xml 文件
<?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>
和代码
<?php
$xml = file_get_contents("test.xml");
$per = preg_replace('/<question[sS]+?>|</question>|<test>|
</test>|<?xml[sS]+?>/i', "", $xml);
$array = explode("n", $per);
function filter($str)
{
return !preg_match('/^[s]*$/', $str);
}
$array = array_filter($array, "filter");
var_dump ($array);
?>
简单的一行。
$array = array_filter(array_map('trim', file('example.xml')), 'strlen');
但是,为什么要使用正则表达式来分析 XML 文档?我建议您改用本机DOMDocument
或SimpleXMLElement
。
DOMDocument
示例:
$dom = new DOMDocument;
$dom->loadXMLFile('example.xml');
$xpath = new DOMXPath($dom);
$q2a1 = $xpath->evaluate('string(/question[@id="2"]/answer[@id="1"])');
SimpleXMLElement
示例:
$xml = new SimpleXMLElement('example.xml', 0, true);
$q2a1 = (string)$xml->xpath('/question[@id="2"]/answer[@id="1"]')->item(0);
首先替换所有空格或空格,如果未返回,则检查是否为空
function filter($str)
{
$string = preg_replace('/s+/', '', $str);
if($string !== ""):
return $string;
endif;
}
$array = array_filter($array, "filter");
var_dump ($array);