1

I have a $custom_size variable in PHP that I need to extract a Width and Height number from.

The format of the string can contain different values so it is not ALWAYS in the proper format. Meaning sometimes it may have characters that do not belong.

The one thing that will always be the same though is the Width value will always be the number on the LEFT of the x and the Height value will always be the number on the RIGHT side of the x

Some sample strings may be in this format below...

$custom_size = '48"x40"'

$custom_size = '48x40'

$custom_size = '48"Wx40"H'

$custom_size = '48Wx40H'

$custom_size = '48 x 40'

I need help extracting the number on the left and assigning it to a $width variable and the number on the right to a $height variable.

In addition to the example strings, I imagine there could be more possibilities of similar strings as well but always similar.

I would appreciate any help in how to do this, I am not that great with Regular Expressions and I think that might be required due to all the possible combinations?

Basically need to figure out the best way to assign all numbers to the LEFT of an x or X to a $width variable and all numbers to the RIGHT of it to a $height variable

JasonDavis
  • 48,204
  • 100
  • 318
  • 537

4 Answers4

2

So, I mentioned in a comment this way:

function get_number($str) {
    preg_match_all('!\d+!', $str, $matches);
    return $matches;
}

If, as you said, you need to extract all the numbers and put together, use this:

$left = join("", get_number(strtok($custom_size, "x")));
$right = join("", get_number(strtok("\n")));

It will work like that: "4"8 "x"5 "2" => $left=48, $right=52

Serge Seredenko
  • 3,541
  • 7
  • 21
  • 38
1

I hope this will suffice. Works with all the above mentioned dimensions.

$custom_size = '48"Wx40"H';
$varx=explode('x',$custom_size);
$width=intval($varx[0]);//48
$height=intval($varx[1]);//40

EDIT

$varx=explode('x',strtolower($custom_size));
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
  • 1
    I think this might be the most flexible and simple route possibly since it allows the string to be in many formats and will still return the proper values – JasonDavis Oct 06 '13 at 03:25
  • 1 minor issue to make this perfect...if it can allow for the `x` to be capital or lowercase.... so `x` or `X` ? – JasonDavis Oct 06 '13 at 03:33
  • 1
    Oh I got an idea, ill just make everything capital or lowercase and then process it – JasonDavis Oct 06 '13 at 03:35
0

you can use explode()

$size = explode("x" , $custom_size);
$width = $size[0];
$height = $size[1];
Mubin
  • 4,325
  • 5
  • 33
  • 55
0

just throw away what you don't want:

$custom_size=preg_replace("/[^0-9x]/","",$custom_size);
Cwissy
  • 2,006
  • 15
  • 14