0

どこかに日付を含む文字列を処理しています。この文字列に日付を表​​示するには、さまざまな方法があります。

「… 01.11.2009 18:00-21:00 …」または「… 01.11.2009 18:00-02.11.2009 15:00 …」または「… 01.11.2009 18:00 …」

日付がどのように表示されるかに関係なく、開始日「01.11.2009 18:00」のみが必要です。したがって、2 つの一致がある場合、それは最初の 1 つだけです。これをphpの完全な文字列から分離/分解するにはどうすればよいですか。何か案が?

正規表現でパターンを作成し、それを preg_match と照合する必要があると思います。これが道ですか?残念ながら、私は正規表現にはあまり興味がありません。ランダムな文字列から単一の日付ブロックを取得するのを手伝ってくれる人はいますか?

4

5 に答える 5

1
$matches = array();
$desired_date = '';
preg_match('/\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}/', $string_containing_dates, $matches);
if (isset($matches[0])) $desired_date = $matches[0];
于 2009-10-27T01:04:14.820 に答える
0

試す:

$s = "… 01.11.2009 18:00-21:00 …… 01.11.2009 18:00-02.11.2009 15:00 …… 01.11.2009 18:00 …";
preg_match_all('!(\d{2}\.\d{2}\.\d{4}) \d{2}:\d{2}(-\d{2}:\d{2}|-\d{2}\.\d{2}\.\d{4} \d{2}:\d{2})?!', $s, $matches);
print_r($matches[1]);
于 2009-10-27T01:01:12.580 に答える
0

日付が次のようにフォーマットされている場合、各日付の文字数は常に同じになります。次に、単純な substr() を使用して、最初の X 文字を取得できます。

// example date strings
$date = date('m.d.Y h:i:S');
$date2 = date('m.d.Y h:i:S', strtotime('+50 days'));
$date_str = $date . '-' . $date2;

// get the first 10 characters for the date
$match = substr($date_str, 0, 10);
于 2009-10-27T01:02:08.337 に答える
0

これを試してください:

preg_match_all(
    '/([0-9]{2}\.[0-9]{2}\.[0-9]{4} [0-9]{2}:[0-9]{2})' // linebreak added
    . '(?:-(?:[0-9]{2}\.[0-9]{2}\.[0-9]{4} )?(?:[0-9]{2}:[0-9]{2})?)?/',
    '" 01.11.2009 18:00-21:00 " or " 01.12.2009 18:00-02.12.2009 15:00 " '
    . 'or " 01.01.2009 18:00 "',
    $matches
);

print_r($matches[1]);
// "01.11.2009", "01.12.2009", "01.01.2009"
于 2009-10-27T01:05:03.250 に答える
0

以下の関数を使用して、その形式の最初の日付を抽出できます。

function find_date($string) {
    preg_match("/\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}/",$string,$matches);
    return $matches[0];
}
于 2009-10-27T01:06:52.147 に答える