簡體   English   中英

正則表達式-返回拆分匹配

[英]Regular expression - return split matches

我有代碼:

<?php

$pattern = '~(?(?=hello 2)(hello 2)|hello (1))~';


$subjects = [];
$subjects[] = <<<EOD
test hello 2 test
EOD;


$subjects[] = <<<EOD
test hello 1 test
EOD;


$result = preg_match_all($pattern, $subjects[0], $matches);
assert($matches[1][0] == 'hello 2');

$result = preg_match_all($pattern, $subjects[1], $matches);
assert($matches[1][0] == '1');

我想在一個數組中有所有匹配項-數組中有2個項目(輸入字符串,第一個或第二個表達式的結果),但是現在我得到了3個數組中的項目(輸入字符串,結果,空)或(輸入字符串,空,結果) 。 在var dump中,它是:

實際狀態:

array(3) {
  [0] =>
  array(1) {
    [0] =>
    string(7) "hello 2"
  }
  [1] =>
  array(1) {
    [0] =>
    string(7) "hello 2"
  }
  [2] =>
  array(1) {
    [0] =>
    string(0) ""
  }
}
array(3) {
  [0] =>
  array(1) {
    [0] =>
    string(7) "hello 1"
  }
  [1] =>
  array(1) {
    [0] =>
    string(0) ""
  }
  [2] =>
  array(1) {
    [0] =>
    string(1) "1"
  }
}

我想要:

array(2) {
  [0] =>
  array(1) {
    [0] =>
    string(7) "hello 2"
  }
  [1] =>
  array(1) {
    [0] =>
    string(7) "hello 2"
  }
}
array(2) {
  [0] =>
  array(1) {
    [0] =>
    string(7) "hello 1"
  }
  [1] =>
  array(1) {
    [0] =>
    string(1) "1"
  }
}

您需要對?|使用分支重置 ?|

$pattern = '~(?|(?=hello 2)(hello 2)|hello (1))~';

IDEONE演示

這樣,您將避免非參與組出現在結果匹配數組中。

有關更多詳細信息,請參見regular-expressions.info的分支重置組

暫無
暫無

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

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