本文目錄一覽:
php將字元串中的阿拉伯數字轉換為中文數字
為了方便調用我喜歡使用函數的方法
?php
function numToWord($num)
{
$chiNum = array(‘零’, ‘一’, ‘二’, ‘三’, ‘四’, ‘五’, ‘六’, ‘七’, ‘八’, ‘九’);
$chiUni = array(”,’十’, ‘百’, ‘千’, ‘萬’, ‘億’, ‘十’, ‘百’, ‘千’);
$chiStr = ”;
$num_str = (string)$num;
$count = strlen($num_str);
$last_flag = true; //上一個 是否為0
$zero_flag = true; //是否第一個
$temp_num = null; //臨時數字
$chiStr = ”;//拼接結果
if ($count == 2) {//兩位數
$temp_num = $num_str[0];
$chiStr = $temp_num == 1 ? $chiUni[1] : $chiNum[$temp_num].$chiUni[1];
//當以1開頭 都是十一,十二,以十開頭的 我們就取$chiUni[i]也就是十
當不是以1開頭時,而是以2,3,4,我們取這個數字相應的中文並拼接上十
$temp_num = $num_str[1];
$chiStr .= $temp_num == 0 ? ” : $chiNum[$temp_num];
//取得第二個值並的到他的中文
}else if($count 2){
$index = 0;
for ($i=$count-1; $i = 0 ; $i–) {
$temp_num = $num_str[$i]; //獲取的個位數
if ($temp_num == 0) {
if (!$zero_flag !$last_flag ) {
$chiStr = $chiNum[$temp_num]. $chiStr;
$last_flag = true;
}
}else{
$chiStr = $chiNum[$temp_num].$chiUni[$index%9] .$chiStr;
//$index%9 index原始值為0,所以開頭為0 後面根據循環得到:0,1,2,3…(不知道為什麼直接用$index而是選擇$index%9 畢竟兩者結果是一樣的)
//當輸入的值為:1003 ,防止輸出一千零零三的錯誤情況,$last_flag就起到作用了當翻譯倒數第二個值時,將$last_flag設定為true;翻譯第三值時在if(!$zero!$last_flag)的判斷中會將其攔截,從而跳過
$zero_flag = false;
$last_flag = false;
}
$index ++;
}
}else{
$chiStr = $chiNum[$num_str[0]]; //單個數字的直接取中文
}
return $chiStr;
}
echo numToWord(12345);
?
結果截圖:
php 獲取字元串的數字
?php
header(‘content-type:text/html;charset=utf-8;’);//utf-8編碼,避免亂碼
$str=’2、小孩自費項目:香溪古堡 (0.8米以下免票,0.8—1.2米25元,1.2米以上50元)br/’;
$data=array();//找到的數字放這裡
$newdata=array();//替換的格式放這裡
$num=preg_match_all(“/[^](\d+\.)?\d+/”,$str,$re,PREG_PATTERN_ORDER);//用正則表達式把數字全找出來
foreach($re[‘0’] as $value){
preg_match(“/(\d+\.)?\d+/”,$value,$value2);//會匹配到非 # 61618的字元,所以還要清除掉那些非 # 61618得字元
$data[]=$value2[0];
}
$data=array_unique($data);//清理相同值(避免重複替換)
foreach($data as $value)
$newdata[]=”span style=\”color:red\”{$value}/span”;
$str=str_replace($data,$newdata,$str);//替換
echo “{$str}br/”;//輸出測試
?
親,在php5.3下通過測試,發現bug請告訴我,注釋不夠請追問喲!
php怎麼把字元串中的數字取出來
解決這個問題的辦法,可以使用如下方法:
一、通過遍歷字元串,並對字元進行判斷。
二、使用正則表達式,取出數字。
原創文章,作者:KXSH,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/141158.html