Reputation: 85
This is what I have tried so far getting year from any type of string.
<?php
$variable = [
'Well year is 1967 month jan',
'year is 1876 but month January',
'HOLLA April Evening 2017',
'DOLLA-May 2020',
'OH-YESApril 2019 (IGNORE)',
'Just a sample String without year ok lets just add 1'
];
foreach ($variable as $value) {
if(ContainsNumbers($value)){
$input = preg_replace('/^[^\d]*(\d{4}).*$/', '\1', $value);
$input = (int)$input;
if($input>1000 && $input<2100)
{
var_dump($input);
}
}
}
function ContainsNumbers($String){
return preg_match('/\\d/', $String) > 0;
}
?>
Here is an output of above code
int(1967)
int(1876)
int(2017)
int(2020)
int(2019)
The only thing I want now is getting month from the string .
For month I am getting help from this link but no luck so far :-
I don't know what to add in $data
$str = 'December 2012 Name: Jack Brown';
$ptr = "/^(?P<month>:Jan(?:uary)?|Feb(?:ruary)?|Dec(?:ember)?) (?P<year>:19[7-9]\d|2\d{3}) (Name:(?P<name>(.*)))/";
var_dumb(preg_match($ptr, $str, $data););
Upvotes: 0
Views: 215
Reputation: 85
Well Chris haas has explained it very clearly but any one would like to use array approach then kindly use this :-
<?php
$variable = [
'Well year is 1967 month jan',
'year is 1876 but month January',
'HOLLA April Evening 2017',
'DOLLA-May 2020',
'OH-YESApril 2019 (IGNORE)',
'Just a sample String without year ok lets just add 1'
];
$months = array(
'January' => 'jan',
'February' => 'feb',
'March' => 'mar',
'April' => 'apr',
'May' => 'may',
'June' => 'jun',
'July ' => 'jul',
'August' => 'aug',
'September' => 'sep',
'October' => 'oct',
'November' => 'nov',
'December' => 'dec',
);
foreach ($variable as $string) {
foreach($months as $key => $value){
if (strpos($string, $value) !== false) {
var_dump($value) ;
}
if (strpos($string, $key) !== false) {
var_dump($value) ;
}
}
}
die();
?>
Output
string(3) "jan"
string(3) "jan"
string(3) "apr"
string(3) "may"
string(3) "apr"
Upvotes: 0
Reputation: 55427
Traditionally, almost everyone calls the third parameter to preg_match
$matches
, so I'm going to go with the nomenclature here.
If the RegEx matches, the third parameter will be an array with numeric indexes for each items, as well named-indexes if you have any named matches. So you are looking for:
if(preg_match($ptr, $str, $matches)){
var_dump($matches);
}
Which will give you:
Array
(
[0] => December 2012 Name: Jack Brown
[month] => December
[1] => December
[year] => 2012
[2] => 2012
[3] => Name: Jack Brown
[name] => Jack Brown
[4] => Jack Brown
[5] => Jack Brown
)
Upvotes: 1