简体   繁体   中英

Regex Multiple Capture of Group

I'm using regex to capture the dimensions of ads

Source content is an HTML File, and I'm trying to capture for content that looks like:

size[200x400,300x1200] (could be 1-4 different sizes)

I'm trying to an array with the different sizes in it

My capture code looks like this:

$size_declaration = array();
$sizes = array();
$declaration_pattern = "/size\[(\d{2,4}x\d{2,4}|\d{2,4}x\d{2,4},){1,4}\]/";
$sizes_pattern = "/\d{2,4}x\d{2,4}/";

$result = preg_match($declaration_pattern, $html, $size_declaration);
if( $result ) {
    $result = preg_match_all($sizes_pattern, $size_declaration[0], $sizes);
    var_dump($sizes);
}

The code above produces usable results:

$sizes = array(
  [0] => array (
    [0] => '200x400',
    [1] => '300x1200'
  )
)

but it takes quite a bit of code. I was thinking it was possible to collect the results with a single regex, but I couldn't find a result that works. Is there a way to clean this up a bit?

It's not very practical to turn it into a single expression; it would be better to keep them separate; the first expression finds the boundaries and does rudimentary content checks on the inner contents, the second expression breaks it down into individual pieces:

if (preg_match_all('/size\[([\dx,]+)\]/', $html, $matches)) {
    foreach ($matches[0] as $size_declaration) {
        if (preg_match_all('/\d+x\d+/', $size_declaration, $sizes)) {
            print_r($sizes[0]);
        }
    }
}

This one is a little simpler:

$html = "size[200x400,300x600,300x100]";
if (($result = preg_match_all("/(\d{2,4}x\d{2,4}){1,4}/", $html, $matches)) > 0)
    var_dump($matches);
// 
// $matches => 
//     array(
//          (int) 0 => array(
//              (int) 0 => '200x400',
//              (int) 1 => '300x600',
//              (int) 2 => '300x100'
//          ),
//          (int) 1 => array(
//              (int) 0 => '200x400',
//              (int) 1 => '300x600',
//              (int) 2 => '300x100'
//          )
//     )
// 

The only way is to repeat the 4 eventual sizes in the pattern:

$subject = <<<LOD
size[523x800]
size[200x400,300x1200]
size[201x300,352x1200,123x456]
size[142x396,1444x32,143x89,231x456]
LOD;

$pattern = '`size\[(\d{2,4}x\d{2,4})(?:,(\d{2,4}x\d{2,4}))?(?:,(\d{2,4}x\d{2,4}))?(?:,(\d{2,4}x\d{2,4}))?]`';

preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
foreach ($matches as &$match) { array_shift($match); }

print_r($matches);

The pattern can also be shorten using references to capture groups:

$pattern = '`size\[(\d{2,4}x\d{2,4})(?:,((?1)))?(?:,((?1)))?(?:,((?1)))?]`';

or with the Oniguruma syntax:

$pattern = '`size\[(\d{2,4}x\d{2,4})(?:,(\g<1>))?(?:,(\g<1>))?(?:,(\g<1>))?]`';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM