tags:

views:

85

answers:

2

Here's some PHP code:

$myText = 'ABC #12345 (2009) XYZ';

$myNum1 = null;

$myNum2 = null;

How do I add the first set of numbers from $myText after the # in to $myNum1 and the second numbers from $myText that are in between the () in to $myNum2. How would I do that?

A: 

If you have an input string of form "123#456", you can do

$tempArray = explode("#", $input);
if (sizeof($tempArray) != 2) {
    echo "OH NO! Something bad happened!";
}
$value1 = intval($tempArray[0]);
$value2 = intval($tempArray[1]);
echo "Result: " . ($value1 + $value2);
Alex
The second number ground doesn't show
Tony
+2  A: 
preg_match('/#(\d+).*\((\d+)\)/', $myText, $matches);
$myNum1 = $matches[1];
$myNum2 = $matches[2];

assuming you have something like:

" stuff ... #123123 stuff (456456)"

that will give you $myNum1 = 123123 $myNum2 = 456456

Janek
Thanks but that's not working.
Tony
Because, with the last number group, I see a ")" in the results!
Tony
The wrong closing paren was escaped. It should be: \((\d+)\)
bish
Thanks! fixed it up
Janek