H 在那里 - 在这里发布第一时间 - 我会不让你知道我是"PHP和Perl的新手",因为这将在下面变得非常明显。
下面是我写的一个脚本,用于抓取银行的资产金额,将其乘以 3% 并显示结果。我在下面解释我的心流想法,并显示我得到的结果与我应该得到的结果进行比较。我的猜测是,我不能用仍在数组中的值进行数学运算。在我开始做一些数学之前,我是否缺少一个内爆过程。
我正在抓取的 URL 在我的服务器上,因此请随意运行。
<?php
// scrape page content of credit union
$dataassets = file_get_contents('http://ablistings.com/boise-project.htm');
// define regular expression to grab credit union's assets amount
$regexassets = '/members,'s(.+?)'smillion/';
// run the preg_match
preg_match($regexassets,$dataassets,$matchassets);
// print the second key of the array [1] which is just the numerical value (in this case $214.4)
$assetsamount = print_r($matchassets[1]);
// add 3% to the value of $214.4, so first we multiple .03 by value
$three_percent_increase = ($assetsamount * .03); // should egual 6.432
// now add the percentage to the orginal asset amount - in this case 6.432 + 214.4 which = 220.832
$final_sum = ($three_percent_increase + $assetsamount);
echo $final_sum;
// sum should be $220.832 but the sum this script produces is $214.41.03
?>
<?php
$dataassets = 'members, $214.40 million';
// define regular expression to grab credit union's assets amount
$regexassets = '/members,'s'$(['d.]+?)'smillion/';
// run the preg_match
preg_match($regexassets,$dataassets,$matchassets);
// print the second key of the array [1] which is just the numerical value (in this case $214.4)
$assetsamount = $matchassets[1];
var_dump($assetsamount);
// add 3% to the value of $214.4, so first we multiple .03 by value
$three_percent_increase = ($assetsamount * .03); // should egual 6.432
var_dump($three_percent_increase);
// now add the percentage to the orginal asset amount - in this case 6.432 + 214.4 which = 220.832
$final_sum = ($three_percent_increase + $assetsamount);
echo $final_sum;
您的代码存在 2 个问题:
您不会跳过原始金额的
$
。我已经修改了正则表达式来执行此操作。您正在将
print_r
的结果分配给$assetsamount
。print_r
不返回它打印的值,它只返回1
。所以它增加了 3% 到 1,导致1.03
.
当它打印$214.41.03
时,它实际上是两件事:214.4
来自print_r($matchassets[1])
,1.03
来自echo $final_sum
。