Home > php教程 > PHP源码 > 百度面试题:解析字符串四则表达式

百度面试题:解析字符串四则表达式

PHP中文网
Release: 2016-05-25 17:12:53
Original
992 people have browsed it


<?php
 
/**
 * @author yusaint
 * @copyright 2011
 */
function cal($expr)
{
    $splittedBy_multi = explode(&#39;*&#39;, $expr); // (12/3) (2) (12) (12/4)
    $temp = array();
    print_r($splittedBy_multi);
    foreach ($splittedBy_multi as $k => $v) {
 
        $splittedBy_divided = explode(&#39;/&#39;, $v);
        if (count($splittedBy_divided) > 1) {
            $temp[$k] = intval($splittedBy_divided[0]) * intval($splittedBy_divided[0]);
            foreach ($splittedBy_divided as $val) {
                $temp[$k] /= intval($val);
            }
        } else
            $temp[$k] = intval($v);
    }
    return array_product($temp);
 
 
}
$expr = "10-4+123+100*98*8/100*4*3+3-12/3/4*2*12*12/4+4-8+12/3*12+12";
$splittedBy_plus = explode(&#39;+&#39;, $expr); //0=>(4*3)  1=>(3-12/3/4*2*12*12/4) 2=>(4-8)
$temp = array();
foreach ($splittedBy_plus as $k => $v) {
    $splittedBy_minus = explode(&#39;-&#39;, $v); // 3 12/3/4*2*12*12/4
    if (count($splittedBy_minus) > 1) //(3) (12/3/4*2*12*12/4) (4) (8)
        {
        $temp_minus = array();
        foreach ($splittedBy_minus as $key => $value) {
            $temp_minus[$key] = cal($value);
        }
        $minus = 2 * $temp_minus[0];
        foreach ($temp_minus as $value) {
            $minus -= (int)$value;
        }
        $temp[$k] = $minus;
    } else {
        $temp[$k] = cal($v);
    }
 
 
}
$sum = 0;
foreach ($temp as $value) {
    $sum += $value;
}
echo &#39;the parsed value is:&#39; . $sum."\n";
echo &#39;the original value is:&#39;.(10-4+123+100*98*8/100*4*3+3-12/3/4*2*12*12/4+4-8+12/3*12+12);
?>
Copy after login

                   

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template