簡體   English   中英

正則表達式多次捕獲組

[英]Regex Multiple Capture of Group

我正在使用正則表達式來捕獲廣告的尺寸

源內容是一個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'
  )
)

但是需要很多代碼。 我當時以為可以用一個正則表達式來收集結果,但是找不到有效的結果。 有辦法清理一下嗎?

將其轉換為單個表達式不是很實際。 最好將它們分開; 第一個表達式找到邊界,並對內部內容進行基本的內容檢查,第二個表達式將其分解為各個部分:

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

這個簡單一些:

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

唯一的方法是在模式中重復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>))?]`';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM