gpt4 book ai didi

php - 在 PHP 中从 HTML 中提取一段数据的最简单方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 15:39:31 25 4
gpt4 key购买 nike

我正在处理大部分无效 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">&nbsp;</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>

最佳答案

如果您确定开始和结束 span 标签在同一行上。 . .

$ 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 视为文本文件,并对 span 标签进行 grep。

$ grep '[</]span>' yourfile.html

关于php - 在 PHP 中从 HTML 中提取一段数据的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4934616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com