将字符串与值数组匹配并返回键

时间:2012-09-25 23:52:46

标签: php arrays

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

$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

依旧......

知道怎么做?

5 个答案:

答案 0 :(得分:1)

$index = -1;
foreach ($arr_month as $k => $v) {
   if (strstr($mystring, $v)) {
      $index = $k;
      break;
   }
}
// exists with $index set

答案 1 :(得分: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

答案 2 :(得分: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;
}
?>

答案 3 :(得分:1)

您可以使用带数组键的可选搜索参数执行此操作:

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

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

答案 4 :(得分: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
)

所以它当天放弃了,但它确实正确地确定了月份和年份。

使用更现代的DateTime api会对您的输入失败(是法语还是英语的混合?)

但它确实适用于以下内容:

$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
相关问题