【发布时间】:2014-01-22 02:52:07
【问题描述】:
我正在处理一个 XML 文件,我需要获取 <section> 标签内的所有内容。
现在我正在使用这个正则表达式:
<?php preg_match_all('/<section[^>]*>(.*?)<\/section>/i', $myXmlString, $results);?>
<section> 标签内的代码相当复杂。它包括数学方程式和类似的东西。
在我的本地机器上,正则表达式完美运行。
它是 apache 2.2.22 (Ubuntu) 之上的 php 5.3.10
但是在我的登台服务器中不起作用。 它是 apache 2.2.15 (Red Hat) 之上的 php 5.3.3
我会问两个问题:
php 5.3.3 的 preg_match_all 有什么问题吗?
有没有更好的方式来表达正则表达式?
--编辑:未成功使用的正则表达式的变体--
<?php preg_match_all('/<section[^>]*>(.*?)<\/section>/is', $myXmlString, $results);?>
<?php preg_match_all('/<section[^>]*>(.*?)<\/section>/ims', $myXmlString, $results);?>
<?php preg_match_all('#<section[^>]*>(.*?)<\/section>#ims', $myXmlString, $results);?>
<?php preg_match_all('#<section[^>]*>([^\00]*?)<\/section>#ims', $myXmlString, $results);?>
--编辑:为什么我没有使用解析器?
XML 由两个<sections> 组成。每个部分对考试的 n 个问题进行分组。
每个问题都可以包含由其自己的 XML 表示的数学方程式。一个方程可能是这样的:
<inlineequation><m:math baseline="-16.5" display="inline" overflow="scroll"><m:mrow><m:mtable columnalign="left"><m:mtr><m:mtd><m:mrow><m:mo stretchy="true">[</m:mo><m:mrow><m:mtable columnalign="right"><m:mtr><m:mtd><m:mn>4</m:mn></m:mtd><m:mtd columnalign="right"><m:mrow><m:mo>-</m:mo><m:mn>9</m:mn></m:mrow></m:mtd><m:mtd columnalign="right"><m:mrow><m:mn>54</m:mn></m:mrow></m:mtd></m:mtr><m:mtr><m:mtd columnalign="right"><m:mrow><m:mo>−</m:mo><m:mn>28</m:mn></m:mrow></m:mtd><m:mtd columnalign="right"><m:mo>−</m:mo><m:mn>1</m:mn></m:mtd><m:mtd columnalign="right"><m:mo>−</m:mo><m:mn>14</m:mn></m:mtd></m:mtr></m:mtable></m:mrow><m:mo stretchy="true">]</m:mo></m:mrow></m:mtd></m:mtr></m:mtable></m:mrow></m:math></inlineequation>
我需要该代码保留 XML(无数组),因为我会将代码原样传递给 jQuery 插件,该插件将呈现方程式(它看起来像 LaTeX 方程式)。
如果我解析 XML,则很难再次为方程式创建字符串并将其定位在问题陈述中的正确位置。
【问题讨论】:
-
为什么不使用 xml 解析器?使用正则表达式解析 XML 存在一些问题,例如,sanity。
-
由于未转义的分隔符,手头的代码在任何一个版本上都不起作用。
-
另外,你打扰reading the documentation了吗?您似乎错过了 PHP 5.3.6 的一个特定点。
-
它在 PHP 5.3.3 no 5.3.6 上失败。我的第一种方法是使用解析器,但在这些部分中有很多代码我需要保留为 XML,因为它将由 jQuery 插件解释以呈现数学方程式。
标签: php regex xml-parsing