如何从混合字符串中获得一年? (PHP)

时间:2018-05-19 01:07:24

标签: php arrays date

我有这样的字符串:

$str[] = "November 28th, 2014 | 0 - 9, 2014, Karthik Nallamuthu";<br/>
$str[] = "October 6th, 2015 | 0 - 9, 2015, D. Imman";<br/>
$str[] = "November 22nd, 2017 | 0 - 9, 2017";<br/>
$str[] = "December 18th, 2009 | 0 - 9";<br/>
$str[] = "December 18th, 2009 | 0 - 9";<br/>
$str[] = "October 30th, 2015 | 0 - 9, 2015, Sean Roldan";<br/>
$str[] = "December 18th, 2009 | 0 - 9";<br/>
$str[] = "November 25th, 2011 | 0 - 9, 2011 |";<br/>

我想从这个数组中获得只有年份值 - 字符串请帮助我。

2 个答案:

答案 0 :(得分:1)

使用DateTime::createFromFormat是一种方法,假设您的所有数据格式相同:

foreach ($str as $s) {
    $date = DateTime::createFromFormat('F jS, Y+', $s);
    echo "year of '$s' is ". (int)$date->format('Y') . "\n";
}

您的数据输出:

year of 'November 28th, 2014 | 0 - 9, 2014, Karthik Nallamuthu' is 2014
year of 'October 6th, 2015 | 0 - 9, 2015, D. Imman' is 2015
year of 'November 22nd, 2017 | 0 - 9, 2017' is 2017
year of 'December 18th, 2009 | 0 - 9' is 2009
year of 'December 18th, 2009 | 0 - 9' is 2009
year of 'October 30th, 2015 | 0 - 9, 2015, Sean Roldan' is 2015
year of 'December 18th, 2009 | 0 - 9' is 2009
year of 'November 25th, 2011 | 0 - 9, 2011 |' is 2011

答案 1 :(得分:0)

您也可以这样使用,如果数组格式相同且介于两个分隔符或字符串之间,

 foreach ($str as $key => $row) {
    echo "year of '$row' is <b>".extract_unit($row,",","|") . " <b></br>";
 }
 function extract_unit($string, $start, $end)
 {
  $pos = stripos($string, $start);

  $str = substr($string, $pos);

  $str_two = substr($str, strlen($start));

  $second_pos = stripos($str_two, $end);

  $str_three = substr($str_two, 0, $second_pos);

  $unit = trim($str_three); // remove whitespaces

  return $unit;
 }