Search code examples
phpregexpreg-matchpreg-match-all

Extract size dimensions from a string using PHP


Can someone help me to extract dimensions from a string similar to thse strings

Extending Garden Table 100 x 200 x 300 cm white
Extending Garden Table 200 x 200 cm black
Extending Garden Table 200 cm black Large

i need it to only ouput 100 x 200 x 300 cm or 200 x 200 cm or 200 cm, according what the string contains

I started with below code in case it could help a bit

$string1 = "Extending Garden Table 100 x 200 x 300 cm white"; 
$test    = get_dimensions($string1);  //need it to output 100 x 200 x 300 cm


function get_dimensions($str) {
    preg_match_all('/[0-9]{1,2}\X[0-9]{1,2}/i', $str, $matches);
    //preg_match_all('!\d+!', $str, $matches);
    return $matches;
}

Solution

  • You can use

    \d+(?:\s*x\s*\d+)*\s*cm\b
    

    See the regex demo. Details:

    • \d+ - one or more digits
    • (?:\s*x\s*\d+)* - zero or more sequences of:
      • \s*x\s* - x enclosed with zero or more whitespaces
      • \d+ - one or more digits
    • \s* - zero or more whitespaces
    • cm - a cm word
    • \b - a word boundary

    See the PHP demo:

    function get_dimensions($str) {
        preg_match_all('/\d+(?:\s*x\s*\d+)*\s*cm\b/i', $str, $matches);
        return $matches[0];
    }
    $string1 = "Extending Garden Table 100 x 200 x 300 cm white"; 
    $test    = get_dimensions($string1);  //need it to output 100 x 200 x 300 cm
    print_r($test);
    // => Array ( [0] => 100 x 200 x 300 cm )
    

    To extract numbers with fractional part, add (?:[,.]\d+)? (an optional occurrence of a comma or dot and then one or more digits) after each \d+ in the pattern above:

    \d+(?:[,.]\d+)?(?:\s*x\s*\d+(?:[,.]\d+)?)*\s*cm\b
    

    See this regex demo.