0

The text is similar to this: +1191–1405 Holy Damage The numbers can change as well as the Damage type. Like +777-1444 Fire Damage ect.

What I want to do is extract the two numbers. So from the first example I want 1191 and 1405 and I need them to be integers not strings.

I've read up on preg_ stuff and such a bit and can do simple searches and parsing but i'm not quite at this level. I'm guessing I need to extract whatever numbers that are after + but before -, and after - discarding everything else.

Paul Duncan
  • 302
  • 1
  • 5
  • 19

2 Answers2

2

Use this:

preg_match('/\+(\d+)-(\d+)/', $text, $match);

Now $match[1] contains the first number, $match[2] contains the second number.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Where `$text = "+1191–1405 Holy Damage"`? – codingbiz Jun 07 '14 at 00:53
  • 1
    Yes, `$text` contains the text you're matching. – Barmar Jun 07 '14 at 00:54
  • When I do `preg_match('/\+(\d+)-(\d+)/', '+1191–1405 Holy Damage', $match);` and do a `echo $match[1];` im getting nothing returned. If I use `print_r($match)` its a blank array. Please advise. – Paul Duncan Jun 07 '14 at 01:06
  • 2
    The character before the second number in your text is not an ASCII minus sign, it's Unicode code point 342387. If that's what you're searching for, you need to put that character into the regular expression in place of the minus sign. – Barmar Jun 07 '14 at 01:12
  • Wow, how deceiving! Thanks! – Paul Duncan Jun 07 '14 at 01:14
1

Because I hate pattern matching and avoid it whenever possible:

function getNumbersFromString($str){
    $splt = explode(' ', $str); // split by spaces
    $sub = substr($splt[0], 1); // get rid of leading +
    return explode('-', $sub); // return split by -
}

// Array ( [0] => 777 [1] => 1444 )
print_r(getNumbersFromString('+777-1444 Fire Damage'));
// Array ( [0] => 1191 [1] => 1405 )
print_r(getNumbersFromString('+1191-1405 Holy Damage'));
Andrew
  • 1,571
  • 17
  • 31
  • Nice, this is a good alternative method. Im stubborn and want to get the other to work as well though. Both useful. – Paul Duncan Jun 07 '14 at 01:09