Php 抓取 - 如何捕获源代码中的变量?

Php Scraping - How do I catch the variable in the source code?

在下面的html代码中,我想捕获变量“1.31”。感谢您的帮助。

Source Code
    <div style="font-size:20px">1.31 <i class="fa fa-try"></i> <span style="text-decoration: line-through; color:#919191; font-size: 14px; margin-top: 7px; margin-right: 5px; float:left" itemprop="price" content="1.55">1.55 <i class="fa fa-try" itemprop="priceCurrency" content="TL"></i></span>
    <link itemprop="availability" href="http://schema.org/InStock">
    </div>

<?php

$url = "https://www.oyunfor.com/knight-online/gb-gold-bar";

$url_connect = file_get_contents($url);

preg_match('@<div style="font-size:20px">(.*?)<i@si',$url_connect,$results);

print_r($results);

?>

你的代码工作得很好,但是我建议做一个小的修改:

<?php
$markup = <<<HTML
    <div style="font-size:20px">1.31 <i class="fa fa-try"></i> <span style="text-decoration: line-through; color:#919191; font-size: 14px; margin-top: 7px; margin-right: 5px; float:left" itemprop="price" conten
    <link itemprop="availability" href="http://schema.org/InStock">
    </div>
HTML;

preg_match('@<div style="font-size:20px">(.*?)<i@si', $markup, $results);
var_dump($results[1]);

输出是:

string(5) "1.31 "

更新:

正如您在下面的评论中指出的那样,如果您实现内部 http 请求而不是使用示例中所示的静态标记来实现内部 http 请求,那么您不会 得到预期的结果如您在问题中所示,从某个远程服务器获取该标记。

原因是您收到的标记与您在问题中给出的示例不匹配。它略有不同,导致您的正则表达式不匹配。这就是为什么正则表达式被认为是解析此类标记的糟糕方法的主要原因:当主题标记发生一些微小变化时,它们很容易崩溃。

更具体地说:您收到的标记实际上是无效的。您可能没有意识到这一点,因为您在浏览器中将其可视化。但请注意,浏览器会尝试 "fix" 使其可用。对于调试,您需要在没有此类中间层的情况下查看事物,以了解您实际处理的内容。在这里,您应该将收到的标记转储到某个日志文件中。

无论如何:您可以稍微修改正则表达式以使其再次匹配。这就是我的建议,使用它会再次产生如上所示的相同输出。

@<div\s+[^>]*style="?font-size:20px"?[^>]*>(.*?)<i@si