Question

What is the best way to decompose the following string:

$str = '/input-180x129.png'

Into the following:

$array = array(
    'name' => 'input',
    'width' => 180,
    'height' => 129,
    'format' => 'png',
);
Was it helpful?

Solution

I would just use preg_split to split the string into several variables and put them into an array, if you must.

$str = 'path/to/input-180x129.png';

// get info of a path
$pathinfo = pathinfo($str);
$filename = $pathinfo['basename'];

// regex to split on "-", "x" or "."
$format = '/[\-x\.]/';

// put them into variables
list($name, $width, $height, $format) = preg_split($format, $filename);

// put them into an array, if you must
$array = array(
    'name'      => $name,
    'width'     => $width,
    'height'    => $height,
    'format'    => $format
);

After Esailija's great comment I've made new code that should work better!

We simply get all matches from a preg_match and do pretty much the same we did on previous code.

$str = 'path/to/input-180x129.png';

// get info of a path
$pathinfo = pathinfo($str);
$filename = $pathinfo['basename'];

// regex to match filename
$format = '/(.+?)-([0-9]+)x([0-9]+)\.([a-z]+)/';

// find matches
preg_match($format, $filename, $matches);

// list array to variables
list(, $name, $width, $height, $format) = $matches;
//   ^ that's on purpose! the first match is the filename entirely

// put into the array
$array = array(
    'name'      => $name,
    'width'     => $width,
    'height'    => $height,
    'format'    => $format
);

OTHER TIPS

This might be a slow & stupid solution, but it is easier to read:

$str = substr($str, 1);       //  /input-180x129.png => input-180x129.png
$tokens = explode('-', $str);
$array = array();
$array['name'] = $tokens[0];
$tokens2 = explode('.', $tokens[1]);
$array['format'] = $tokens2[1];
$tokens3 = explode('x', $tokens2[0]);
$array['width'] = $tokens3[0];
$array['height'] = $tokens3[1];
print_r($array);

// will result:
$array = array(
    'name' => 'input',
    'width' => 180,
    'height' => 129,
    'format' => 'png',
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top