0

所以我有一个几个月的数组:

$arr_month = array(
    1=>'january',
    2=>'february',
    3=>'march',
    4=>'april',
    5=>'may',
    6=>'june',
    7=>'july',
    8=>'august',
    9=>'september',
    10=>'october',
    11=>'november',
    12=>'december'
);

我也有字符串(我知道,它们看起来很奇怪......)看起来像:

23 de january del 2003
12 de may de 1976
6 de february de 1987

我想要的是找到字符串中的月份并将其与数组匹配并返回数组键。

所以:

23 de january del 2003 returns 1
12 de may de 1976 returns 5
6 de february de 1987 returns 2

等等...

知道怎么做吗?

4

5 回答 5

1

这应该适合你。

$dateString = "23 de january del 2003"; // as an example
$exploded = explode (" ", $dateString); // separate the string into an array of words
$month = $exploded[2]; // we want the 3rd word in the array;
$key = array_search ($month, $arr_month); // lets find the needle in the haystack
print $key;

产量1

有关更多信息,请参见http://php.net/manual/en/function.array-search.php

于 2012-09-26T00:03:56.413 回答
1

你应该可以这样做:

<?php

function getMonth($time){
    $matches = array();
    preg_match("/[0-9] de ([a-z]+) de/", $time, $matches);
    return date('n',strtotime($matches[1]));
}
?>

那么你甚至不需要你的月份数组:D

编辑如果你出于某种原因想要阵列在那里:

<?php
function getMonth($time){
    $matches = array();
    $pattern = "/[0-9] de ([a-z]+) de/";
    preg_match($pattern, $time, $matches);
    $month = $matches[1];
    $arr_month (
        1=>'january',
        2=>'february',
        3=>'march',
        4=>'april',
        5=>'may',
        6=>'june',
        7=>'july',
        8=>'august',
        9=>'september',
        10=>'october',
        11=>'november',
        12=>'december'
    );
    return in_array($month, $arr_month) ? array_search($month, $arr_month) : false;
}
?>
于 2012-09-26T00:15:20.237 回答
1

您可以使用带有数组键的可选搜索参数来做到这一点:

$matchedKeys = array_keys($arr_month, "november");
var_dump($matchedKeys);
// array(1) { [0]=> int(11) }

如您所见,这将返回所有匹配键的数组

于 2012-09-26T00:17:39.133 回答
1
$index = -1;
foreach ($arr_month as $k => $v) {
   if (strstr($mystring, $v)) {
      $index = $k;
      break;
   }
}
// exists with $index set
于 2012-09-25T23:56:21.217 回答
1

如果您尝试解析日期,请记住 PHP 可以为您做到这一点(尽管这取决于您的输入数据的任意性 - 如果您提前知道日期格式,这显然更可靠)。

例如:

print_r(date_parse("6 de february de 1987"));

给出:

Array
(
    [year] => 1987
    [month] => 2
    [day] => 
    [hour] => 
    [minute] => 
    [second] => 
    [fraction] => 
    [warning_count] => 2
    [warnings] => Array
        (
            [14] => Double timezone specification
            [22] => The parsed date was invalid
        )

    [error_count] => 2
    [errors] => Array
        (
            [0] => Unexpected character
            [2] => The timezone could not be found in the database
        )

    [is_localtime] => 1
    [zone_type] => 0
)

所以它在当天被放弃了,但它确实正确地识别了月份和年份。

在您的输入中使用更现代的DateTimeapi 失败(是法语和英语的混合体吗?)

但它确实适用于以下情况:

$d = new DateTime("6th february 1987", new DateTimeZone("UTC"));
print $d->format("Y-m-d H:i:s") . "\n";'

给出:

1987-02-06 00:00:00
于 2012-09-26T00:32:31.473 回答