3

ここではいくつかの例を示します。

  1. Some text A
  2. Some text A 8:00-19:00
  3. 8:00-19:00
  4. Some text A 8:00-19:00 Some text B

上記の各ケースについて、キャプチャする必要があります (可能な場合):

  • 時刻 ( 8:00-19:00)
  • はじまり ( Some text A)
  • 終わり ( Some text B)

このパターン#^(.*?) ?(\d{1,2}:\d{2}-\d{1,2}:\d{2})?$#で、キャプチャできます (例 2 から):

  • Some text A
  • 8:00-19:00

しかし、パターンの最後に(.*)orを追加しても、残りの行をキャプチャすることはできません。(.*?)

手伝って頂けますか?ありがとうございました!

4

4 に答える 4

2

preg_splitを使用するのはどうですか?

$tests = array(
    'Some text A',
    'Some text A 8:00-19:00',
    '8:00-19:00',
    'Some text A 8:00-19:00 Some text B'
);

foreach ($tests as $test) {
    $res = preg_split('/(\d\d?:\d\d-\d\d?:\d\d)/', $test, -1,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
    print_r($res);
}

出力:

Array
(
    [0] => Some text A
)
Array
(
    [0] => Some text A 
    [1] => 8:00-19:00
)
Array
(
    [0] => 8:00-19:00
)
Array
(
    [0] => Some text A 
    [1] => 8:00-19:00
    [2] =>  Some text B
)
于 2012-07-30T09:43:14.993 に答える
1
<?php

    $pattern = <<<REGEX
/
(?:
    (.*)?\s*                    #Prefix with trailing spaces
    (
        (?:\d{1,2}:\d{1,2}-?)   #(dd:dd)-?
        {2}                     #2 of those
    )                           #(The time)
    \s*(.*)                     #Trailing spaces and suffix
    |
    ([a-zA-Z ]+)                #Either that, or just text with spaces
)
/x
REGEX;

    preg_match($pattern, "Some text A 8:00-19:00 Some text B", $matches);

    print_r($matches);

配列$matchesには、必要なすべてのパーツが含まれます。

編集:テキストだけにも一致するようになりました。

于 2012-07-29T17:04:22.137 に答える
0

わかりました...ケースのシナリオが正確にはわかりません。

3 つのオプション グループを一致させたいと考えています (一致させたくないケース シナリオを提供しない限り、おそらく「不正な形式の」入力に一致するでしょう)。

これはすべての例で機能しますが、ケース 1 では、「テキスト A」が $matches[1] の代わりに $matches[0] と $matches[3] に表示されます。

/^([A-Za-z ]*?)([0-2]{0,1}[0-9]\:[0-6][0-9]\-[0-2]{0,1}[0-9]\:[0-6][0-9])?([A-Za-z ]*?)$/
于 2012-07-29T17:42:55.720 に答える
0

あなたの主な問題は、数字のグループをその後に追加?してオプションにしたことだと思います(これは望ましくないと思います)。

これは私のために働く/^(.*) ?(\d{1,2}:\d{2}-\d{1,2}:\d{2}) ?(.*)$/

<?

$str = "Some text A 8:00-19:00 Some text B";
$pat = "/^(.*) ?(\d{1,2}:\d{2}-\d{1,2}:\d{2}) ?(.*)$/";

if(preg_match($pat, $str, $matches)){
   /*

    Cases 2, 3 and 4

    Array
    (
        [0] => Some text A 8:00-19:00 Some text B
        [1] => Some text A 
        [2] => 8:00-19:00
        [3] => Some text B
    )

   */
}else{
   /* Case 1 */
}

?>
于 2012-07-29T17:04:55.507 に答える