无法让 preg_match() 工作以从另一个网站获取内容

Can't get preg_match() to work to fetch content from another website

我正在尝试从带有正则表达式的外部网站获取标签的值,preg_match() 但它不起作用。

我的代码

$file = file_get_contents('http://www.investing.com/indices/us-spx-500');

$regexp = '/\<span class\=\"arial_26 inlineblock pid-166-last\" id\=\"last_last\" dir\=\"ltr\"\>(.*?)\<\/span>/';
preg_match($regexp, $file, $string1);

print_r(array_values($string1));

我需要匹配的标签是:

<span class="arial_26 inlineblock pid-166-last" id="last_last" dir="ltr">1,880.02</span>

1,880.02 = (.*?)

我需要获取指数 S&P500 的值。我知道这可能是版权问题。这仅供私人使用。正如您在 $regexp 中看到的那样,我需要转义所有已完成的特殊字符。我试图从 TXT 文件中获取标签并且它正在工作,所以我知道代码是 correct/linked。一定是正则表达式的问题。有人能弄清楚吗,还是我错过了什么?数组为空。

我认为这是因为 class 中的空格,所以我尝试 \s 但它没有用。

我也试过以下没有进展:

$regexp = '#<span class="arial_26 inlineblock pid-166-last" id="last_last" dir="ltr">(.*?)</span>#';

如果你从网站上查看源代码,它应该是那个特定的标签。

提前致谢。

只需删除 ? 并且不要在单引号字符串中使用转义。

$text = '<span class="arial_26 inlineblock pid-166-last" id="last_last" dir="ltr">1,880.02</span>';
$regex = '{<span class="arial_26 inlineblock pid-166-last" id="last_last" dir="ltr">(.*)</span>}';
preg_match($regex, $text, $matches);
echo $matches[1].PHP_EOL;

eval.in demo

你只需要在双引号字符串中转义(模式字符除外),在这种情况下 ? 完全没有影响。您的常规组模式 (.*?) 表示 'Zero or more characters, or zero'.

编辑:

? 的不相关性在上述特定字符串中是真实存在的,但在更广泛的上下文中(即 <div><span class="arial_26 inlineblock pid-166-last" id="last_last" dir="ltr">1,880.02</span></div>)并非如此。

检索所需文本的最正确方法是 - 总的来说 -

它不起作用,因为如果您不向它传递用户代理,investing.com 不会 return 任何东西。以下代码可以正常工作:

$options = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad 
  )
);
$context = stream_context_create($options);
$file = file_get_contents('http://www.investing.com/indices/us-spx-500',false,$context);
$regexp = '/\<span class=\"arial_26 inlineblock pid-166-last\" id=\"last_last\" dir\=\"ltr\"\>(.*?)<\/span>/';
preg_match($regexp, $file, $string1);
print_r(array_values($string1));

另外,你只需要转义那个字符串中的"/,不需要转义=<>

PHP 有内置工具来解析 HTML,正则表达式在这里特别不合适,因为您正在寻找具有 id 属性的节点!

// you set the user_agent with the name you want
$opts = [ 'http' => [ 'user_agent' => 'obliglobalgu' ] ];
// to create a stream context 
$context = stream_context_create($opts);
// set the stream context for DOMDocument::loadHTMLFile 
libxml_set_streams_context($context); 

$url = 'http://www.investing.com/indices/us-spx-500';

libxml_use_internal_errors(true); // avoid eventual libxml errors to be displayed

$dom = new DOMDocument;
$dom->loadHTMLFile($url);

$spanNode = $dom->getElementById('last_last');

if ($spanNode)
    echo $spanNode->nodeValue;

libxml_clear_errors();