1

I have clients you enter bedrooms as 1 + 2 instead of entering the overall total which in this case would be 3. There is method in PHP that will allow me to take a simple string and generate the sum value?

$bedrooms = '1 + 2';
Tim
  • 403
  • 1
  • 6
  • 20
  • 2
    Why not cleanup the validation? So that clients DON'T enter 1+3? Might be the cleaner way to go, as you might open yourself up to something like 1m + 3child, etc; – Jakub Feb 29 '12 at 18:43
  • What if I enter '2 & maybe a 3rd'? Require a number, have a comment/textfield for further instructions. – Wrikken Feb 29 '12 at 18:53
  • I have to leave it this way as 1 + 2 means one bedroom on main floor and two bedrooms on second floor and this how they like it displayed. Now I am getting into mirroring listings for my clients and the providers I am mirror to do not want it this way. I leave as is and try the answers below. Thanks for the suggestions. – Tim Feb 29 '12 at 19:02
  • display and input are not the same thing, get discrete usable input, then format the display any way you like. –  Feb 29 '12 at 19:04

4 Answers4

3

You could do something like this:

$bedrooms = array_sum(explode("+", str_replace(" ", "", "1 + 2")));
Travesty3
  • 14,351
  • 6
  • 61
  • 98
2

Look up eval - That should do the trick.

But ensure that you have a good regular expression to ensure that the input will not do any harm

e.g. `^[1-9]+ *(+ [1-9]+)$'

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
  • 1
    @T - Knowing the vulnerabilities and still being able to use it safely isn't ;) +1 For the sanitation regex Ed! – Lix Feb 29 '12 at 18:47
  • Weird thing that eval in Perl makes code safer - it implements exceptions! – Ed Heal Feb 29 '12 at 18:51
1

parse that string by + into array add the values

Har
  • 4,864
  • 2
  • 19
  • 22
0

try this

    $bedrooms = 1 + 2;
    $pattern = '/([a-zA-Z \+\-])+/';
    $replacement = '+';
    echo array_sum(explode('+', preg_replace($pattern, $replacement, $bedrooms)));

just to make sure some characters are in the input string

Junaid
  • 2,084
  • 1
  • 20
  • 30