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.

2

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@seoppc That would take you less than a minute to test. But yes, it would.
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.
}

Comments

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.

Comments

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;

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.