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

2
  • 1
    If numbers are integer, that will help. Commented Oct 6, 2013 at 3:15
  • do you want 48W or just 48 etc? Commented Oct 6, 2013 at 3:16

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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));

3 Comments

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
1 minor issue to make this perfect...if it can allow for the x to be capital or lowercase.... so x or X ?
Oh I got an idea, ill just make everything capital or lowercase and then process it
0

you can use explode()

$size = explode("x" , $custom_size);
$width = $size[0];
$height = $size[1];

Comments

0

just throw away what you don't want:

$custom_size=preg_replace("/[^0-9x]/","",$custom_size);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.