0

I am trying to parse following text in variable...

$str = 3,283,518(10,569 / 2,173)

And i am using following code to get 3,283,518

    $arr = explode('(',$str);
    $num = str_replace(',','',$arr[0]); //prints 3283518

the above $str is dynamic and sometimes it could be only 3,283,518(means w/o ()) so explode function will throw an error so what is the best way to get this value? thanks.

seoppc
  • 2,766
  • 7
  • 44
  • 76

4 Answers4

3
$str = "3,283,518(10,569 / 2,173)";

preg_match("/[0-9,]+/", $str, $res);
$match = str_replace(",", "", array_pop($res));

print $match;

This will return 3283518, simply by taking the first part of the string $str that only consists of numbers and commas. This would also work for just 3,283,518 or 3,283,518*10,569, etc.

kba
  • 19,333
  • 5
  • 62
  • 89
0

Probably going to need more information from you about how dynamic $str really is but if its just between those values you could probably do the following

if (strpos($str, '(' ) !== false) {
     $arr = explode('(',$str);
     $num = str_replace(',','',$arr[0]);
} else {
     //who knows what you want to do here.
}
Deano
  • 176
  • 1
  • 4
0

If you are really sure about number format, you can try something like: ^([0-9]+,)*([0-9]+) Use it with preg_match for example. But if it is not a simple format, you should go with an arithmetic expressions parser.

Guillaume Poussel
  • 9,572
  • 2
  • 33
  • 42
0

Analog solution:

    <?php

$str = '3,283,518(10,569 / 2,173)';

if (strstr($str, '('))
{
    $arr = explode('(',$str);
    $num = str_replace(',','',$arr[0]);
}
else
{
    $num = str_replace(',','',$str);
}

    echo $num;

?>
AKOP
  • 1,000
  • 7
  • 10