0

DBオプションから返される文字列があり、ユーザーは日付形式を設定できます:

F j, Y

get_date()これは(今日の場合)、関数で次の値を返します。

string 'September 24, 2012' (length=18)

次に、その文字列を分割する連想配列が必要です。

array( 
    'day'   => 24,
    'month' => 'September',
    'year'  => 2012
)

ユーザーが日付を設定する方法がわからないので、簡単には言えないという問題がありますF = month, j = day, Y = yearphpdate()関数が許可するものはすべて、システムで許可されます。

質問:どうすればそれらを「一致」させることができますか? 何かが月/日/年/時間/...であるかどうかを教えてくれる、私が監督したネイティブ関数はありますか?

編集:最大。使用できるPHPバージョンはPHP 5.2.1です

4

4 に答える 4

4

PHP 5.3 以降を使用している場合は、次を使用しますDateTime::createFromFormat

$date = DateTime::createFromFormat($inputFormat, $gotDate);

$result = array(
    'day' => (int)$date->format('j'),
    'month' => $date->format('F'),
    'year' => (int)$date->format('Y')
);
于 2012-09-29T15:13:28.007 に答える
1

私の意見では、そもそもその文字列をデータベースに保存するのではなく、タイムスタンプを使用するべきです。

それを行うと、次のようなものを使用できます。

$dateTime = new DateTime($theTimestamp);
$date = array(
    'day' => $dateTime->format('j'),
    'month' => $dateTime->format('F'),
    'year' => $dateTime->format('y'),
);

配列に何を入れたいかについて柔軟にしたい場合は、次のような関数を作成できます。

function buildDateArray($theTimestamp, $elements) {
    $dateTime = new DateTime($theTimestamp);
    $date = array();
    foreach($elements as $key => $format) {
        $date[$key] = $dateTime->format($format);
    }
}

$theArray = buildDateArray($theTimestamp, array(
    'day' => 'j',
    'month' => 'F',
    'year' => 'y',
));

注:DateTimeは 5.2.0 以降で使用できます

于 2012-09-29T15:13:02.067 に答える
1

PHP 5.3 を手元に持っていないと書いたように (本当に残念です)、文字列を「手動で」解析する必要があります。PCRE 正規表現の隣には、 もありsscanfます。例:

$date = 'September 24, 2012';
$result = sscanf($date, '%s %2d, %4d', $month, $day, $year);
$parsed = array(
    'day'   => $day,
    'month' => $month,
    'year'  => $year
);
var_dump($parsed);

出力:

array(3) {
  'day' =>
  int(24)
  'month' =>
  string(9) "September"
  'year' =>
  int(2012)
}

これにより、フォーマットに従って入力日付文字列が既に解析されます。これをより柔軟にする必要がある場合は、パターンを動的に構築し、値を結果配列に関連付ける必要があります。

これを行う別の例をコンパイルしました。少し壊れやすいかもしれませんが(メモをいくつか追加しました)、機能します。当然のことながら、これを関数にラップして、エラー状態をより適切に処理しますが、コードを生のままにして、それがどのように機能するかをよりよく示します。

// input variables:
$date = 'September 24, 2012';
$format = 'F j, Y';

// define the formats:
$formats = array(
    'F' => array('%s',  'month'),  # A full textual representation of a month, such as January or March
    'j' => array('%2d', 'day'),    # Day of the month, 2 digits with or without leading zeros
    'Y' => array('%4d', 'year'),   # A full numeric representation of a year, 4 digits
    # NOTE: add more formats as you need them
);

// compile the pattern and order of values
$pattern = '';
$order = array();
for($l = strlen($format), $i = 0; $i < $l; $i++) {
    $c = $format[$i];

    // handle escape sequences
    if ($c === '\\') {
        $i++;
        $pattern .= ($i < $l) ? $format[$i] : $c;
        continue;
    }

    // handle formats or if not a format string, take over literally
    if (isset($formats[$c])) {
        $pattern .= $formats[$c][0];
        $order[] = $formats[$c][1];
    } else {
        $pattern .= $c;
    }
}

// scan the string based on pattern
// NOTE: This does not do any error checking
$values = sscanf($date, $pattern);

// combine with their names
// NOTE: duplicate array keys are possible, this is risky,
//       write your own logic this is for demonstration
$result = array_combine($order, $values);

// NOTE: you can then even check by type (string/int) and convert
//       month or day names into integers

var_dump($result);

この場合の結果は次のようになります。

array(3) {
  'month' =>
  string(9) "September"
  'day' =>
  int(24)
  'year' =>
  int(2012)
}

メモを大事にしてください。書く前に、PHP マニュアルのユーザー ノートを確認しましたが、そこで提供されている関数は 1 つの特定のパターンを解析するためだけのものですが、このバリアントはある程度拡張可能である必要があります。その形式が 1 つしかない場合は、自然に sscanf 文字列を非動的に作成できます。

参照: PHP 5.2 (またはそれ以前) の date_create_from_format と同等

また、wordpressなので月名が翻訳されている場合がありますのでご注意ください。

また、タイムスタンプ形式でも投稿の日付を取得できると確信しています。プラグインの場合、文字列を解析する代わりに、投稿 ID に基づいてその値を取得する方が負担が少ないかもしれません。

最後に、最低 PHP バージョンがあるのは Wordpress だけです。それは、プラグインにも正確な最低バージョンが必要であるという意味ではありません。特に概要を説明した場合、PHP 5.2 はもはやサポートされていません (サポートされていません)。プラグインのユーザーに、PHP バージョンを更新する必要があることを伝えてください。

WordPress はまだ PHP のバージョンに関する警告を出していないようです。ブラウザと独自のソフトウェアで何らかの形で停止します ;) その悪い習慣を真似する必要はありません。ユーザーに危険にさらされていることを伝え、彼らを怖がらせます(または、光沢のあるポップアップバブルを実行して、メッセージをより脅威の少ない方法で伝えます。ユーザーに善意を持ってサービスを提供すると、両方に勝つものがありますあなたの良い姿勢を示すために、ある種の優雅なフォールバックを行います)。

参照: PHP 5.3 と互換性のない Wordpress のバージョンはありますか?

興味があれば、PHP.net ( https://wiki.php.net/rfc/releaseprocess ) で概説されている PHP の現在のリリース サイクルを見つけることができます。

于 2012-09-30T18:32:45.480 に答える
0

ネイティブphpクラスで答えの最初の部分をすでに見つけましたDateTime: Just use date_parse( get_date() );. PHP 5.2 以降で利用可能

// @example
'year' => int 2012
'month' => int 9
'day' => int 24
'hour' => boolean false
'minute' => boolean false
'second' => boolean false
'fraction' => boolean false
'warning_count' => int 0
'warnings' => 
   array
   empty
'error_count' => int 0
'errors' => 
   array
   empty
'is_localtime' => boolean false

この回答は、、 などにマップjする方法がわからないという問題をまだ解決していません。dayFmonth

于 2012-09-29T15:14:09.627 に答える