我正在处理一小部分大部分无效的 HTML,并且我需要提取一小部分数据。考虑到大多数“标记”都是无效的,我认为将所有内容加载到 DOM 中并不是一个好的选择。此外,对于这个简单的情况来说,这似乎有很大的开销。
这是我的标记示例:
(a bunch of invalid markup here with unclosed tags, etc.)
<TD><span>Something (random text here)</span></TD>
(a bunch more invalid markup here with more unclosed tags.)
<TD><span>Something (random text here)</span></TD>
部分不会在文档中的任何地方重复,因此我相信一个简单的正则表达式就可以解决问题。
但是,我对正则表达式很糟糕。
我应该使用正则表达式吗?有没有更简单的方法来做到这一点?如果可能的话,我只想提取 Something 之后的文本,即(此处为随机文本)部分。
提前致谢!
编辑-
HTML 的精确示例(我省略了之前的内容,即供应商使用的无效标记。我相信它与本示例无关):
<div class="FormTable">
<TABLE>
<TR>
<TD colspan="2">In order to proceed with login operation please
answer on the security question below</TD>
</TR>
<TR>
<TD colspan="2"> </TD>
</TR>
<TR>
<TD><label class="FormLabel">Security Question</label></TD>
<TD><span>What is your city of birth?</span></TD>
</TR>
<TR>
<TD><label class="FormLabel">Answer</label></TD>
<TD><INPUT name="securityAnswer" class="input" type="password" value=""></TD>
</TR>
</TABLE>
</div>
最佳答案
如果您确定开始和结束跨度标签位于一行上。 。 .
$ cat test.php
<?php
$subject = "(a bunch of invalid markup here with unclosed tags, etc.)
<TD><span>Something (random text here)</span></TD>
(a bunch more invalid markup here with more unclosed tags.)";
$pattern = '/<span>.*<\/span>/';
preg_match($pattern, $subject, $matches);
print_r($matches);
?>
$ php -f test.php
Array
(
[0] => <span>Something (random text here)</span>
)
如果您不确定 Span 标签是否在同一行,可以将 html 视为文本文件,并使用 grep 查找 Span 标签。
$ grep '[</]span>' yourfile.html
关于php - 在 PHP 中从 HTML 中提取数据的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4934616/