我正在尝试从标记为preg_match()
的RegEx的外部网站获取值,但它无效。
我的代码
$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 = (.*?)
我需要获取indice S&amp; P500的值。我知道这可能是版权问题。这仅供私人使用。正如你在$regexp
中看到的那样,我需要逃避所有已完成的特殊字符。我试图从TXT文件中获取一个标签并且它正在工作,所以我知道代码是正确的/链接的。必须是RegEx的问题。有人可以搞清楚,还是我错过了什么?数组是空的。
我认为这是因为课堂上有空格,所以我尝试了\s
但是没有用。
我还尝试了以下方法而没有取得进展:
$regexp = '#<span class="arial_26 inlineblock pid-166-last" id="last_last" dir="ltr">(.*?)</span>#';
如果您检查网站上的源代码,则应该是该特定标记。
提前致谢。
答案 0 :(得分:2)
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();
答案 1 :(得分:1)
它不起作用,因为如果您未向其传递用户代理,invest.com不会返回任何内容。以下代码正常运行:
$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));
此外,您只需要在该字符串中转义“和 / ,无需转义 = ,&lt; < / strong>和&gt;
答案 2 :(得分:0)
只需删除?
,不要在单引号字符串中使用转义。
$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 强>
你必须只在双引号字符串内转义(模式字符除外),在这种情况下?
完全没有影响力。您的常规群组模式(.*?)
表示零个或多个字符,或零&#39;。
?
的不相关性在上述特定字符串中是真实的,但不是在更广泛的背景下(即<div><span class="arial_26 inlineblock pid-166-last" id="last_last" dir="ltr">1,880.02</span></div>
)。
检索所需文本的最正确方法是 - answer by Casimir et Hippolyte
- 对所有效果