Reputation: 306
Here is the regex
which is removing characters and keeping only digits in a string. This working fine. Please read below examples which are not working for only one case - that is if user enters "4 four" so it can be converted to 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"
Upvotes: 0
Views: 299
Reputation: 7424
Try this : 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);
Upvotes: 2
Reputation: 12872
The most obvious way is to use str_replace
to replace the strings with numbers. For example...
$nums = [
'one' => 1,
'two' => 2,
'three' => 3,
// etc ...
];
$amount = str_replace(array_keys($nums), array_values($nums), $amount);
Upvotes: 0
Reputation: 298
really you'd have to replace before with 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);
Upvotes: 1