0

次のようなPHP配列あります。

array(10) {
  [1]=>
  string(69) "2013-06-12 11:25:44 [INFO] There are no objectives on the scoreboard"

  [2]=>
  string(53) "2013-06-12 11:42:27 [INFO] [Server] Hi, how are you?"

  [3]=>
  string(86) "2013-06-12 11:43:40 [INFO] Usage: /scoreboard objectives <list|add|remove|setdisplay>"

  [4]=>
  string(95) "2013-06-12 11:57:51 [INFO] /scoreboard objectives add <name> <criteriaType> [display name ...]"

  [5]=>
  string(67) "2013-06-12 11:57:59 [INFO] Added new objective 'test' successfully"

  [6]=>
  string(64) "2013-06-12 11:58:16 [INFO] Showing 3 objective(s) on scoreboard"

  [7]=>
  string(74) "2013-06-12 11:58:16 [INFO] - test: displays as 'test' and is type 'dummy'"

  [8]=>
  string(89) "2013-06-12 11:58:16 [INFO] - anothertest: displays as 'anothertest' and is type 'dummy'"

  [9]=>
  string(110) "2013-06-12 11:58:16 [INFO] - yetanothertest: displays as 'yetanothertestwithanothername' and is type 'dummy'"

  [10]=>
  string(60) "2013-06-12 11:58:17 [INFO] [Server] Dude, stop doing that!"
}

項目 6 から 9 を取得して、それらを新しい配列に入れたいと思います。

これを行うには、次のようにする必要があります: 星と同じ文字数を持つ限り、任意のコンテンツが存在できる星を使用することに注意してください。文字数に関係なく、任意の入力が可能なハッシュタグを使用します。

  1. 次の構文を使用して、配列内の最後のエントリを見つけます。"****-**-** **:**:** [INFO] Showing # objective(s) on scoreboard"
  2. 次の構文を使用して、直接続くエントリをすべて取得します。"****-**-** **:**:** [INFO] - #: displays as '#' and is type '#'"
  3. それらを配列に入れます

私は本当にこれに基づいています。正規表現が役立つことは間違いありませんが、理解できませんでした。

前もって感謝します

**編集: **非常に重要なことを完全に忘れていました。このコメントを読んでください。

4

2 に答える 2

2

考えられるアプローチの 1 つを次に示します。

  • 「表示中...」メッセージ用と「表示中」メッセージ用の 2 つのパターンを作成します。
  • 配列を逆の順序で (最後から最初に) 反復処理し、各文字列をチェックします。
  • 文字列が「Showing pattern」に一致する場合は、結果の各文字列で「Displaying」パターンの一致を確認します。もしそうなら、それをいくつかの容器に入れます。一致した文字列も、おそらくこのコンテナーに配置する必要があります。

考えられる実装の 1 つを次に示します。

$datePattern = '\d{4}-\d{2}-\d{2}';
$timePattern = '\d{2}:\d{2}:\d{2}';
$headerPattern = $datePattern . ' ' . $timePattern . ' \[INFO] ';
$showingPattern = $headerPattern 
    . 'Showing \d+ objective\(s\) on scoreboard';
$messagePattern = $headerPattern 
    . "- [^:]+: displays as '[^']*' and is type '[^']*'";

$results = array();

$i = $max = count($arr);
while ($i--) {
  $msg = $arr[$i];
  if (preg_match("/^$showingPattern/", $msg)) {
    $result = array($msg);
    for ($j = $i + 1; $j < $max; $j++) {
      $nextMsg = $arr[$j];
      if (preg_match("/^$messagePattern/", $nextMsg)) {
        $result[] = $nextMsg;
      }
      else {
        break;
      }
    }
    $results[$i] = $result;
  }
}
var_dump($results);

デモ

于 2013-06-12T10:41:42.510 に答える