这是regex
删除字符并仅保留字符串中的数字。这工作正常。请阅读以下仅适用于一个案例的例子 - 即如果用户输入“4四”,则可将其转换为44。
//1
//with out character
$amount = "44";
$cleanedamount = preg_replace ( '/[^0-9]+/', '', $amount);
var_dump($cleanedamount);
//2
//digit prior
$amount1 = "44usd";
$cleanedamount1 = preg_replace ( '/[^0-9]+/', '', $amount1);
var_dump($cleanedamount1);
//3
//digit later
$amount2 = "usd44";
$cleanedamount2 = preg_replace ( '/[^0-9]+/', '', $amount2);
var_dump($cleanedamount2);
//4
//how to convert "4 four" to "44"
答案 0 :(得分:2)
试试这个:Live Demo
$input = "4 four five";
$numbers = array('0'=> 0, 'zero'=> 0, 'one'=> 1, 'two'=> 2, 'tree'=> 3, 'four'=> 4, 'five'=> 5, 'six'=> 6, 'seven'=> 7, 'eight' => 8, 'nine'=> 9);
$reg = '/[0-9]|zero|one|two|tree|four|five|six|seven|eight|nine/';
preg_match_all($reg, $input, $output);
$out = '';
foreach ($output[0] as $key=>$value){
if (isset($numbers[$value])){
$output[0][$key] = $numbers[$value];
}
$out = $out . $output[0][$key];
}
echo($out);
答案 1 :(得分:1)
你真的必须先用str_replace替换
//4
//how to convert "4 four" to "44"
$amount2 = "44 four";
$amount2=str_replace("four","4",$amount2);
$amount2=str_replace("five","5",$amount2);
...
$cleanedamount2 = preg_replace ( '/[^0-9]+/', '', $amount2);
var_dump($cleanedamount2);
答案 2 :(得分:0)
最明显的方法是使用str_replace
用数字替换字符串。例如......
$nums = [
'one' => 1,
'two' => 2,
'three' => 3,
// etc ...
];
$amount = str_replace(array_keys($nums), array_values($nums), $amount);