如何更改数组的值

时间:2014-03-05 18:34:16

标签: php arrays preg-match

我有这个数组:

BEGIN_BROWSER 54
msie6.0 7
safari5.0.3 5
chrome18.0.1025.308 1
firefox20.0 4
.
.
END_BROWSER

为了让我改变价值,我这样做:

preg_match("/BEGIN_BROWSER(.*)END_BROWSER/is", $awstats, $matches);
            $browser = $matches[0] ;               
          //  print_array($browser);

$newline = "
"; 
            $lines = explode($newline,$browser);
            $results = array();
            foreach($lines as $line) {
                $parts = explode(" ",trim($line),2);
                if( count($parts) < 2) continue;
                else {
                   $results[$parts[0]] = intval($parts[1]);
                }
            }
           $results["InternetExplorer"] = 0;
            foreach($results as $key => $value){
              if(strpos($key,"msie") !== false){
                 $results["InternetExplorer"] += $value;
                 unset($results[$key]);
              }
            }

结果我得到的不是msie =&gt; InternetExplorer。有没有办法可以将它改为Internet Explorer,而且单词之间有空格?感谢

2 个答案:

答案 0 :(得分:1)

您可以使用preg_replace更改字符串:

foreach($results as $key => $value){

    $key = preg_replace('/InternetExplorer/', 'Internet Explorer', $key);

    if(strpos($key,"msie") !== false){

答案 1 :(得分:1)

首先,我建议将\n\r替换为某个特定字符然后只是按特定字符分解字符串,因为不推荐使用分割新行的方式。
现在为解决方案尝试

$browsers = str_replace("\n\r", '~~', $awstats);
$browsers = explode('~~', $browsers);
$results = array();
$results['Internet Explorer'] = 0;
foreach($browsers as $b) {
   $parts = explode(" ",trim($b),2);
   if( count($parts) < 2) continue;
   else {
       if ($parts[0] == 'msie') {
          $results['Internet Explorer'] = $results['Internet Explorer'] + intval($parts[1]);
       }
       else {
          $results[$parts[0]] = intval($parts[1]);
       }
   }
}