php - 将分数转换为小数
问题描述
我有带有 HTML 分数的字符串。如何将它们转换为小数?我需要用它们的值替换分数吗?但是在 1 ⅔ 的情况下就不是那么容易了,因为我需要加上 1。
<?php
$mappingArr = [
'½' => 1/2,
'⅓' => 1/3,
'⅔' => 2/3,
'¼' => 1/4,
'¾' => 3/4,
'⅕' => 1/5,
'⅖' => 2/5,
'⅗' => 3/5,
'⅘' => 4/5,
'⅙' => 1/6,
'⅚' => 5/6,
'⅐' => 1/7,
'⅛' => 1/8,
'⅜' => 3/8,
'⅝' => 5/8,
'⅞' => 7/8,
'⅑' => 1/9,
'⅒' => 1/10
];
$fractionString1 = "⅓ Test something else";
$fractionString2 = "1½ Test (test)";
$fractionString3 = "1 ⅔ Test, test";
// how to convert HTML vulgar fractions to decimals?
// result should be
$fractionStringDecimal1 = "0.33 Test something else";
$fractionStringDecimal2 = "1.5 Test (test)";
$fractionStringDecimal3 = "1.67 Test, test";
?>
解决方案
一种方法是遍历每个字符并检查它是否是数字或分数字符。
代码可能类似于以下内容。我正在使用 unicode 字符串操作(mb_substr 和 mb_strlen),因为分数字符是 uncode 字符。
function convertFractionToDecimals($str){
$result = "";
$number = null;
//iterate over each unicode char in the string
for($i = 0; $i < mb_strlen($str); $i++){
//if current char is a number, save it temporarly
if(is_numeric(mb_substr($str, $i, 1))){
if($number == null){
$number = mb_substr($str, $i, 1);
} else {
$number .= mb_substr($str, $i, 1);
}
continue;
}
//if the current char is a fraction char, resolve it
if(isFraction(mb_substr($str, $i, 1))){
if($number != null){
$result .= $number + resolveFraction(mb_substr($str, $i, 1));
} else {
$result .= resolveFraction(mb_substr($str, $i, 1));
}
continue;
}
//if we have a number in front of the current char, that is a space, check if next char is a space or a fraction
if($number != null && mb_substr($str, $i, 1) === ' ' && $i + 1 < mb_strlen($str) && (mb_substr($str, $i+1, 1) === ' ' || isFraction(mb_substr($str, $i+1, 1)))){
continue;
}
if($number != null){
$result .= $number;
$number = null;
}
//a char, that is not a number nor a fraction will be just added to result
$result .= mb_substr($str, $i, 1);
}
return $result;
}
function getFractionMap(){
return $mappingArr = [
'½' => 1/2,
'⅓' => 1/3,
'⅔' => 2/3,
'¼' => 1/4,
'¾' => 3/4,
'⅕' => 1/5,
'⅖' => 2/5,
'⅗' => 3/5,
'⅘' => 4/5,
'⅙' => 1/6,
'⅚' => 5/6,
'⅐' => 1/7,
'⅛' => 1/8,
'⅜' => 3/8,
'⅝' => 5/8,
'⅞' => 7/8,
'⅑' => 1/9,
'⅒' => 1/10
];
}
function isFraction($char) {
return array_key_exists($char, getFractionMap());
}
function resolveFraction($char){
return getFractionMap()[$char];
}
推荐阅读
- sockets - 关于如何创建信息监控服务器的建议
- html - 如何在 pdf 的每一页上重复水印图片,该 pdf 是从包含几个 page-break-before/after 的 html doc 转换而来的?
- android - 由于 Firebase 尝试在只读数据库中写入崩溃报告,应用程序崩溃
- python - 最长的字母子串 - 从哪里开始
- android - 为什么 Android Studio 忽略 git repo 中的文件以及如何从 git 导入项目?
- php - Guzzle(cURL?) 在服务器和本地的行为不同
- syncfusion - 清除/重置 Syncfusion gridcontrol 剪贴板
- python - 如何从特定地理位置获取 twitter 用户屏幕名称或 UserId?
- kubernetes - Kubenates RunAsUser 被禁止
- python - Python IBM Watson NLU 情感分析 - TypeError: cannot convert dic