Dankorw
Dankorw

Reputation: 47

Returning a string value before given character in PHP

I'm trying to extrapolate year and month from a single string wich in the format mm/yyyy. I'm looking for a function where I can give in input the string, and the character I want for the string to stop being copied. I'd like it to return just the "mm" or "yyyy" part.

Is there any known function that does what I'm trying to do? Or should I just make it myself?

Upvotes: 0

Views: 54

Answers (2)

BreyndotEchse
BreyndotEchse

Reputation: 2230

DateTime::createFromFormat:

$date = DateTime::createFromFormat('m/Y', '10/2014');
$date->format('Y'); //returns 2014
$date->format('m'); //returns 10

$date is now a DateTime object and you can work with it like any other DateTime object.

Alternative: date_parse_from_format

Upvotes: 1

Ali
Ali

Reputation: 3461

list($month, $year) = explode("/", "mm/yyyy");
echo $month; // would display the month
echo $year; // would display the year

List() is used to assign variables as if they were an array, and explode() splits your string into an array using the forward slash as a deliemeter.

DEMO

Upvotes: 3

Related Questions