简体   繁体   English

带有preg_match_all()的php不会产生任何结果

[英]php with preg_match_all() generates no results

I'm trying to use this php script in order to locate a stock quote from yahoo finance. 我正在尝试使用此php脚本来查找来自Yahoo Finance的股票报价。 The problem I'm having is that when the script is run it generates no results. 我遇到的问题是,脚本运行时不会生成任何结果。 This leads me to believe that my regular expression is incorrect, but when I use the same regex on myregextester.com it shows the results that I expect with the given input. 这使我相信我的正则表达式是不正确的,但是当我在myregextester.com上使用相同的regex时,它会显示给定输入所期望的结果。 Any help will be greatly appreciated. 任何帮助将不胜感激。 Also, my php may be incorrect for what I'm trying to do. 另外,我的PHP可能对我要执行的操作不正确。

<html>
<head>
    <title>Stock Quote from Nasdaq</title>
</head>
<body>
    <?php
        // choose stock to look at
        $symbol = 'AMZN';
        echo "<h1> Stock Quote for $symbol </h1>";
        //echo 'this printed (1)<br />';

        $theurl = 'http://finance.yahoo.com/q?s=AMZN';

        //echo 'this printed (2)<br />';

        $contents = file_get_contents($theurl);

        //find the part of the page we want and output it
        if (preg_match_all('/amzn">([0-9]+\.[0-9]+)/', $contents, $matches)) {
            echo "The price for $symbol: ".$matches[1][0];
        } else {
            echo "No Results";
        }
    ?>
</body>
</html>

What you are searching for is: 您要搜索的是:

 <span id="yfs_l10_amzn">221.37</span>

Your regex would succeed for that. 您的正则表达式将为此成功。

So your actual problem is retrieving the page. 因此,您的实际问题是检索页面。 Besides the obnoxious $theurl variable name, you should just use file_get_contents instead of fread etc. 除了令人讨厌的$theurl变量名之外,您应该只使用file_get_contents而不是fread等。

 $contents = file_get_contents($theurl);

Worked in your snippet. 在您的代码段中工作过。

I just downloaded the url http://finance.yahoo.com/q?s=AMZN and looked at the page source. 我刚刚下载了URL http://finance.yahoo.com/q?s=AMZN并查看了页面源代码。 Done a seach for /amzn. 对/ amzn进行了搜索。 One match. 一场比赛。 That was <a href="/marketpulse/AMZN">Market Pul.... Hence no match. 那是<a href="/marketpulse/AMZN">Market Pul....因此没有匹配项。

Need to have a rethink. 需要重新考虑。

Escape the > 转义>

try this: 尝试这个:

preg_match_all('/amzn"\>[0-9]+\.[0-9]+/',$contents, $matches);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM