Reputation: 4369
how can i explode the $123
or USD123
or CAD$123
or 元123
dynamically into
array [0] = "$"
array [1] = 123
?
$keywords = preg_split("/[^0-9]/", "$123");
The above is my testing code, but i can't get $
in array[0]
, any idea?
thanks
Upvotes: 6
Views: 1464
Reputation: 2703
You can use the preg_match with following regex
preg_match('/([^0-9]*)([0-9\.]*)(.*)?/', '$20.99USD', $match);
var_dump($match);
The above will produce
Array
(
[0] => $20.99USD
[1] => $
[2] => 20.99
[3] => USD
)
It can parse $, 20.99, USD as separate index in an array
Upvotes: 0
Reputation: 1732
Try this it would work for all.
$str = 'CAD$123';
$num = filter_var($str, FILTER_SANITIZE_NUMBER_INT);
$curr = explode($num,$str);
echo 'Your currency is '.$curr[0].' and number is '.$num;
Upvotes: 3
Reputation: 2345
you can use this
$txt='$123';
$re1='(\\$)'; # Any Single Character 1
$re2='(\\d+)'; # Integer Number 1
if ($c=preg_match_all ("/".$re1.$re2."/is", $txt, $matches))
{
$c1=$matches[1][0];
$int1=$matches[2][0];
print "($c1) ($int1) \n";
}
All credits to http://txt2re.com
Upvotes: 0
Reputation: 15044
$string = '$123';
$string = preg_match('/^(\D+)(\d+)$/', $string, $match);
echo $match[1]; // $
echo $match[2]; // 123
Breakdown:
^(\D+)
match 1 or more non digit at beggining of string
(\d+)$
match 1 or more digits until end of string
Upvotes: 6