Home >php教程 >PHP源码 >中文数字转阿拉伯数字

中文数字转阿拉伯数字

WBOY
WBOYOriginal
2016-06-06 09:32:301010browse
跳至 [1] [全屏预览]
function strToNum($str){
    $arr1=['零'=>'', '一'=>1, '二'=>2, '三'=>3, '四'=>4, '五'=>5, '六'=>6, '七'=>7, '八'=>8, '九'=>9];
    $arr2=['亿'=>100000000,'千万'=>10000000,'百万'=>1000000,'十万'=>100000,'万'=>10000,'千'=>1000,'百'=>100,'十'=>10];
    preg_match_all('/(零|一|二|三|四|五|六|七|八|九|十|百|千|万|亿)+/i',$str,$result);
    if(empty($result[0][0])) return $str;
    else $tmp=$result[0][0];
    $tmp=str_replace(array_keys($arr1), array_values($arr1), $tmp);
    foreach ($arr2 as $k => $v) {
    	if(strlen($tmp)==1) $tmpArr[1]=$tmp;
    	else if(strpos($tmp, $k)!==false){
    		$tmpArr[$v]=getFromStr('',$k,$tmp);
    		$tmp=getFromStr($k,'',$tmp);
    		if(strlen($tmp)==1) $tmpArr[1]=$tmp;
    	}
    }
   	if(is_array($tmpArr)){
   		$num=0;
   		foreach ($tmpArr as $k => $v) {
   			if(empty($v)) $v=1;
   			$num+=$k*$v;
   		}
   	}

    if(!empty($num)) return str_replace($result[0][0], $num, $str);else return $str;
}

function getFromStr($start,$end,$str)
{
    if(!empty($start)) $str=substr($str,strpos($str,$start)+strlen($start) ,strlen($str)-strlen($start)-strpos($str,$start));
    if(!empty($end)) $str=substr($str,0,strpos($str,$end));
    return $str;
}
Statement:
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
Previous article:PHP简单分页Next article:计算访问次数。