0

I would like to preg_match a number which is multiple of 6.5.

For example : 1300 % 6.5 == 0

I test this expression but it's wrong

$pattern  = '/(6.5)(?:\1)?$/';
$number   = 1300;

$matches = preg_match($pattern, $number);
echo $matches;
esqew
  • 42,425
  • 27
  • 92
  • 132
patricko
  • 43
  • 1
  • 6
  • 5
    Why you don't use the modulo operator? – Rizier123 Nov 05 '14 at 23:41
  • It's not really possible with preg_match. If you derive number patterns from your divisor, you could write a complicated regex pattern, but it's hardly any better than just using the modulo operator. See an example for the rather simple case of divisor = 3 at http://quaxio.com/triple/ – Paul Nov 05 '14 at 23:45
  • Multiply the number by two, and check whether it's integer divisible by 13: `if (0 == ((2*$number)%13))`. In case of **very** large numbers, use GMP: http://php.net/manual/en/book.gmp.php. Using regexps for math is the first step before attempting to use them to parse HTML (mandatory reference: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags ). – LSerni Nov 06 '14 at 00:04
  • I was thinking it would be possible to do it with regex. Finaly the good idea is to multiply the number by two and check whether it's divide by 13. Thanks a lot – patricko Nov 06 '14 at 10:50

1 Answers1

0

Why are you trying to use string manipulation for math ops?

At first I was thinking modulus would be the way to go, but was getting unexpected results, due to the float (6.5).

You could do something like:

$x = (1300 / 6.5);

// If we end up with a decimal at all, then the divisor did not go into the dividend evenly 
$divisible = (false !== stripos($x, '.') ? false: true;

I was thinking it would be easier to use is_float, but it returns true no matter if 6.5 goes into 1300 evenly, because the result is cast as a double due to the 6.5.

Mike Purcell
  • 19,847
  • 10
  • 52
  • 89