TimSum
TimSum

Reputation: 738

Regular Expression to separate dimensions

I'm new to php and I need a hand. I have width by height dimensions which are output to a single string (width x height). I need to separate the width and the height. The dimensions will always be less than 100, but could include decimal values. There's also the possibility of whitespace before or after the dimensions.

Here are a few example dimensions: 8x10, 10x12, 24.5x36.625

I think I could accomplish the task using strpos and substr, but would a regular expression be faster? more elegant? more accurate? [side question: what's a good way to learn regex? are there any books/websites you'd recommend?]

$string=' 8.5x10';
$string=trim($string);
$x = stripos($string,'x');
$size1 = substr($string, 0, $x);
$size2 = substr($string, $x+1);
echo $size1 . '<br />';
echo $size2;

Upvotes: 1

Views: 759

Answers (4)

k102
k102

Reputation: 8079

$string = '8.5x10';
list($width, $height) = explode('x',$string);

Upvotes: 4

Bruce
Bruce

Reputation: 7132

Internet is full of tutorials about regexes, you just need to be a little careful as various families are around (perl, old-school unix...)

Concerning your problem, substtring solution is most probably going to be faster as regexes translate into a finite state machie, which can become fairly complex...

It's good when format is loosely defined, as it allows to quickly (programnmer wise) define a format, check it and retrieve data.

In your case : (\d+(\.\d*)?)x(\d+(\.\d*))

  • \d : match a single digit
  • + previous block appears once or more
  • * previous block appears zero or one or many times
  • ? previous block appears zero or one time
  • () define a block

e.g. : d+ would match 1, 12, 158

Now think that regex can match a subset: aaaa15x15aaaa will be as easy to parse as 15x15

When not to use regex is when you need "context sensitive" parsing (e.g. : format of a line depends of previous information)

Hope this helps

Upvotes: 1

Bojangles
Bojangles

Reputation: 101533

First, get rid of all the whitespace, then split the string on the x character. Using list() makes it easier to split the array into separate variables.

$string = "1.23 x5 ";
$string = str_replace(" ", "", $string);
list($width, $height) = explode("x", $string);

You may also want to cast the values to floating point, just to make sure they're actually numbers:

$width = (float)$width;
$height = (float)$height;

Upvotes: 0

Poonam
Poonam

Reputation: 4631

$string=' 8.5x10';
$array = explode('x',$String);
var_dump($array);

$array[0] => will have size1 , $array[1] => will have size2

Upvotes: 0

Related Questions