Reputation: 75
Can someone help me with a regular expression to get the year and month from a text string?
Here is an example text string:
http://www.domain.com/files/images/2012/02/filename.jpg
I'd like the regex to return 2012/02
.
Upvotes: 2
Views: 464
Reputation: 47976
Depending on your situation and how much your strings vary - you might be able to dodge a bullet by simply using PHP's handy explode()
function.
A simple demonstration - Dim the lights please...
$str = 'http://www.domain.com/files/images/2012/02/filename.jpg';
print_r( explode("/",$str) );
Returns :
Array
(
[0] => http:
[1] =>
[2] => www.domain.com
[3] => files
[4] => images
[5] => 2012 // Jack
[6] => 02 // Pot!
[7] => filename.jpg
)
The explode()
function (docs here), splits a string according to a "delimiter" that you provide it. In this example I have use the /
(slash) character.
So you see - you can just grab the values at 5th and 6th index to get the date values.
Upvotes: 1
Reputation: 24400
This regex pattern would match what you need:
(?<=\/)\d{4}\/\d{2}(?=\/)
Upvotes: 2