PHP 中的 HTML 注释抓取

发布于 2024-08-03 11:58:22 字数 367 浏览 4 评论 0原文

我一直在四处寻找,但尚未找到解决方案。我正在尝试抓取 HTML 文档并获取两个注释之间的文本,但到目前为止还无法成功完成此操作。

我正在使用 PHP,并多次尝试过这里推荐的 PHP Simple DOM 解析器,但似乎无法让它执行我想要的操作。

这是我想要解析的页面(部分):

<div class="class">
  <!-- blah -->
    text
  <!-- end blah -->

  Text I want

  <!-- blah -->
    text
  <!-- end blah -->
</div>

谢谢

I've been looking around but have yet to find a solution. I'm trying to scrape an HTML document and get the text between two comments however have been unable to do this successfully so far.

I'm using PHP and have tried the PHP Simple DOM parser recommended here many times but can't seem to get it to do what I want.

Here's (part of) the page that I wish to parse:

<div class="class">
  <!-- blah -->
    text
  <!-- end blah -->

  Text I want

  <!-- blah -->
    text
  <!-- end blah -->
</div>

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心房的律动 2024-08-10 11:58:22

假设每个注释都不同(即第一部分和第二部分中的“blah”不同),您可以使用一些简单的 strpos 来获取它们之间的所有内容。 正则表达式不是必需的。

$startStr = '<!-- end blah1 -->';
$endStr = '<!-- start blah2 -->';

$startPos = strpos($HTML, $startStr) + strlen($startStr);
$endPos = strpos($HTML, $endStr );

$textYouWant = substr($HTML, $startPos, $endPos-$startPos);

如果两组注释相同,则需要使用 strpos 修改它以找到第二个“blah”offset 参数

Assuming that each comment is different (i.e. "blah" is not the same in the first and second sections), you can use some simple strpos to grab everything between them. Regular expressions are not necessary.

$startStr = '<!-- end blah1 -->';
$endStr = '<!-- start blah2 -->';

$startPos = strpos($HTML, $startStr) + strlen($startStr);
$endPos = strpos($HTML, $endStr );

$textYouWant = substr($HTML, $startPos, $endPos-$startPos);

If the two sets of comments are the same, you'll need to modify this to find the second "blah", using strpos's offset parameter

流心雨 2024-08-10 11:58:22

也许你可以使用正则表达式?

$text = '
<div class="class">
  <!-- blah -->
    text
  <!-- end blah -->

  Text I want

  <!-- blah -->
    text
  <!-- end blah -->
</div>
';

$regex = '/(<!-- end blah -->)(.*?)(<!-- blah -->)/ims';
$match = preg_match_all ($regex, $text, $matches);

Maybe you can use regular expressions?

$text = '
<div class="class">
  <!-- blah -->
    text
  <!-- end blah -->

  Text I want

  <!-- blah -->
    text
  <!-- end blah -->
</div>
';

$regex = '/(<!-- end blah -->)(.*?)(<!-- blah -->)/ims';
$match = preg_match_all ($regex, $text, $matches);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文