Search code examples
phparraysstringdecomposition

PHP String Decomposition


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

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