从http api抓取只需要的字符


Grab only required characters from http api

我从http api收集数据,其中一个api是检查我的剩余信用余额。下面是我想做的,获取file_contents并从接收到的输出中插入剩余的积分。

        $bal =  file_get_contents("http://www.example.com/balancecheck.php?username=123&api_password=123");

this输出如下数据

username = 123
validity = 31/03/2103
remaining credits = 5000
user credits = 3000

现在,我想只抓取5000(这是剩余的学分,并插入到我的db)

我想用爆炸,但运气不好。

从PHP文档:

描述

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

搜索与pattern. 中给出的正则表达式匹配的主题

所以,你需要的是:

preg_match( "/remaining credits = ('d+)/", file_get_contents($url), $matches);
$balance = $matches[1];

编辑:

file_get_contents函数调用之前我有一个额外的$。我以为PHP让你到处放美元符号。现在应该修好了。

编辑2:

我以前有$balance = $matches[0],但它已被纠正。括号('d+)只捕获匹配的数字,并将其添加到$matches数组的末尾。