2012-03-20 117 views
0

所以...我计算所有preg_match的出现次数和求和/添加它的第一部分(“/”之前的数字)有问题。我只想在“/”之前得到数字的平均值。真的很抱歉英文不好。PHP count and sum preg_matches

的script.php

$wyniki=file("wyniki.txt"); 
foreach($wyniki as $w) 
{ 
     preg_match("/^([0-9]{1})\/([0-9]{1})$/",$w,$ar); 
     if(!empty($ar)){ 
     print_r($ar[1].'/'.$ar[2]); 
     echo("\n"); 
     } 
} 

script2.php(失败,但script.php的其他方式)

$file=fopen("wyniki.txt", "r"); 
$read=fread($file, filesize("wyniki.txt")); 
echo($read."\n"); 
//if($read!=trim('')) 
//{ 
     preg_match("/^([0-9]{1})\/([0-9]{1})$/",$read,$ar); 
     //print_r($ar[1].'/'.$ar[2]); 
     print_r($ar); 
     echo("\n"); 
//} 
fclose($file); 

wyniki.txt

5/5 
asd 

4/5 
fgh 
+1

提示:'[0-9] {1}'可被写为'[0-9]'单独。添加'{1}'有点像说“一个苹果是一个苹果”。字符类将自己匹配一个数字。 – 2012-03-20 17:52:35

+0

你在这里做什么?您的正则表达式看起来不错(参见http://www.regexplanet.com/advanced/java/index.html) – haltabush 2012-03-20 17:54:10

+0

我的问题在于创建获取平均值的代码。我所有的尝试,甚至计数$ AR失败;) – crusty 2012-03-20 18:06:44

回答

0

您正则表达式似乎确定。也许你在每行的结尾都有一些空格(你用'$')。您可以通过使用trim()来删除它们。另外,在任何情况下,正则表达式可能都不是最好的解决方案。也许你会更简单地测试'/'的出现,然后使用split()并检查数组[0]是一个数字(is_numeric())。考虑下面的代码:

$wyniki=file("wyniki.txt"); 
foreach($wyniki as $w) { 
if (strpos($w, '/') !== FALSE) { 
    $tarr = split("\/", $w); 
    if (is_numeric($tarr[0])) 
    echo "This is a number: " . $tarr[0]; 
} 
} 

第二码与正则表达式:

$flines = array("5/5","asd","4/5","fgh"); 
$regex = "#^([0-9]{1})\/([0-9]{1})$#"; 
$res = $tot = 0; 
foreach ($flines as $fline) { 
$arr = array(); 
preg_match($regex, $fline, $arr); 
if (is_numeric($arr[1])) { 
    $res += $arr[1]; 
    $tot++; 
} 
} 
$avg = bcdiv($res, $tot, 2); 
echo "Average: $avg"; 
+0

这是正确的,但我仍然不知道如何计算所有出现;)以及如何总结数字之前/;) – crusty 2012-03-20 18:53:33

+0

我编辑了我的代码,它给出了4.5正确。这假设你所有的'/'后面的数字是相等的。 – Jan 2012-03-20 19:25:11

+0

4.5?是的,'/'之后的数字总是5,但之前没有;) – crusty 2012-03-20 20:46:28