正则表达式组的多重捕获

时间:2013-04-12 01:51:47

标签: php regex

我正在使用正则表达式来捕捉广告的尺寸

源内容是一个HTML文件,我正在尝试捕获看起来像这样的内容:

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

我正在尝试使用不同大小的数组

我的捕获代码如下所示:

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

上面的代码产生了可用的结果:

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

但它需要相当多的代码。我认为可以用一个正则表达式收集结果,但我找不到有效的结果。有没有办法清理一下这个?

3 个答案:

答案 0 :(得分:1)

将它变成单个表达式并不是很实际;将它们分开会更好;第一个表达式查找边界并对内部内容进行基本内容检查,第二个表达式将其分解为单个部分:

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

答案 1 :(得分:0)

这个更简单:

$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'
//          )
//     )
// 

答案 2 :(得分:0)

唯一的方法是在模式中重复4个最终尺寸:

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

使用对捕获组的引用也可以缩短模式:

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

或使用Oniguruma语法:

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