本文目錄一覽:
「php」字元串如何轉換成數字?
1.強制類型轉換方式 \x0d\x0a$foo = “1”; // $foo 是字元串類型 \x0d\x0a$bar = (int)$foo; // $bar 是整型 \x0d\x0a\x0d\x0a2.內置函數方式 \x0d\x0a$foo = “1”; // $foo 是字元串類型 \x0d\x0a$bar = intval($foo); // $bar 是整型 \x0d\x0a\x0d\x0a3.格式化字元串方式 \x0d\x0a$foo = “1”; // $foo 是字元串類型 \x0d\x0a$bar = sprintf(“%d”, $foo); // $bar 是字元串類型
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 26位字母轉換成數字
?php
$str=”aa”;//寫你想要算的字元串;
$v;
function getv($s){
$arr=str_split($s,1);
for ($i=0;$istrlen($s);$i++)
{
$v=gett($arr[$i])*getw(strlen($s)-$i-1)+$v;
}
echo $v;
}
function getw($w){
$x=1;
for ($i=0;$i$w;$i++){
$x=26*$x;
}
return $x;
}
function gett($ch){
return (ord($ch)-96);
}
echo getv($str);
?
aa,剛好就是27.你試試吧
php 字元串轉換成數字
1.強制類型轉換方式
$foo = “1”; // $foo 是字元串類型
$bar = (int)$foo; // $bar 是整型
2.內置函數方式
$foo = “1”; // $foo 是字元串類型
$bar = intval($foo); // $bar 是整型
3.格式化字元串方式
$foo = “1”; // $foo 是字元串類型
$bar = sprintf(“%d”, $foo); // $bar 是字元串類型
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/189069.html