Reputation: 4108
So out of all of my php skills, I just suck at regular expressions. I totally understand the concept of it, but I can't write my patterns well. Well I need them for to extract date information from a file path. Here's my code:
#example path
$path='/Users/landonsilla/Desktop/HS Pilot Project/Archive/Cabinet/Documents/2006-11In/Car Park/AR190298.doc';
echo $path."\n\n";
$pattern1 = '/[0-9]{4}[0-9]{2}[0-9]{2}/';#match YYYYMMDD
$pattern2 = '/[0-9]{4} [0-9]{2} [0-9]{2}/';#match YYYY MM DD
$pattern3 = '/[0-9]{4}[-][0-9]{2}/';#match YYYY-MM
$pattern4 = '/20[0-9]{2}/';#match YYYY
if(preg_match($pattern1, $path, $matches)){
$ret=$matches[0].'-'.$matches[1].'-'.$matches[2].' 00:00:00';
}
else if(preg_match($pattern2, $path, $matches)){
$ret=$matches[0].'-'.$matches[1].'-'.$matches[2].' 00:00:00';
}
else if(preg_match($pattern3, $path, $matches)){
$ret=$matches[0].'-'.$matches[1].'-01 00:00:00';
}
else if(preg_match($pattern4, $path, $matches)){
$ret=$matches[0].'-01-01 00:00:00';
}
else{
$ret=date ("Y-m-d H:i:s.", filemtime($path));
}
The $pattern1,2,3,4 variables just don't work. Can somebody please let me know how to change those variables such that I can wind up having $ret be a date in my standard (mysql) format?
Upvotes: 0
Views: 313
Reputation: 12586
First off you need to group your subpatterns using ()
. This will store the results in the matches[]
array as you assumed. Further more the matches are stored in index 1 and up so you need to add 1 to each of your matches in your if/else.
$path='/Users/landonsilla/Desktop/HS Pilot Project/Archive/Cabinet/Documents/2002-11In/Car Park/AR190298.doc';
echo $path."\n\n";
$pattern1 = '/([0-9]{4})([0-9]{2})([0-9]{2})/';#match YYYYMMDD
$pattern2 = '/([0-9]{4})([0-9]{2})([0-9]{2})/';#match YYYY MM DD
$pattern3 = '/([0-9]{4})[-]([0-9]{2})/';#match YYYY-MM
$pattern4 = '/(20[0-9]{2})/';#match YYYY
if(preg_match($pattern1, $path, $matches)){
$ret=$matches[1].'-'.$matches[2].'-'.$matches[3].' 00:00:00';
}
else if(preg_match($pattern2, $path, $matches)){
$ret=$matches[1].'-'.$matches[2].'-'.$matches[3].' 00:00:00';
}
else if(preg_match($pattern3, $path, $matches)){
$ret=$matches[1].'*-*'.$matches[2].'-01 00:00:00';
}
else if(preg_match($pattern4, $path, $matches)){
$ret=$matches[1].'-01-01 00:00:00';
}
else{
$ret=date ("Y-m-d H:i:s.", filemtime($path));
}
Result can be viewed on here.
Upvotes: 1