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 の現在のリリース サイクルを見つけることができます。