How to extract year using preg_match - php

I have textarea where users enter details, I want to extract year from the textarea. The problem is users enter year in different ways.
some users input dates as 1999 or '99 or september 99. how can I use a single regex string to extract year.

This should work for extracting the mentioned dates out of text:
preg_match_all('/(^|\s+)(\d{4}|\'\d{2}|(january|february|march|april|may|june|july|august|september|october|november|december) \d{2})(\s+|$)/i', $text, $matches);
This came to my mind, too (it gives the user a little more freedom):
preg_match_all('/(^|\s+)((january|february|march|april|may|june|july|august|september|october|november|december|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)?(\s|\s?\')(\d{2}|\d{4}))(\s+|$)/i', $text, $matches);
All of the above would be easier when parsed with multiple expressions. Why do you need a single one?
If you simply want to parse a string that contains nothing else than this, you should use PHP's strtotime()-function.

\b\d\d(?:\d\d)?\b
will match a two- or four-digit number. So if your string only contains year numbers, that should be enough.
if (preg_match('/\b\d\d(?:\d\d)?\b/', $subject, $regs)) {
$result = $regs[0];
}

You can try to use strtotime:
strtotime — Parse about any English textual datetime description into a Unix timestamp
date('Y', strtotime($userinput));

[. -]((?:\d\d|')\d\d)$

Extract only digits from your string :
/\b(\d+)\b/

Related

In mysql, how can I select the numeric portion of a field?

I have a table containing free-form phone numbers (e.g. '123-456-7890', '(987) 654-3210', or '123.456.7890') and I'm searching them with a numeric string- e.g., '123456'.
Right now, I'm having to do a bunch of replace(replace(replace(.. ad nauseum functions to strip out errant non-numeric characters then use that 'LIKE' the search value to search.
Anyone know of a simpler way to select only certain characters from a field based on type, not position?
You can use regex in MySQL -
SELECT *
FROM `table`
WHERE `phone` REGEXP '^[12345]'
Here is a working example.
try using regexes. if you want to extarct numbers from a string you can use this:
$string = '123-456-7890';
preg_match_all('/\d+/', $string, $matches);
echo $matches; //will result in only digits
Try splitting up the number into three different values, i.e.
$first = '124';
$second= '456';
$third = '7890';
"WHERE (phone_number LIKE '%$first%' and LIKE '%$second%' and LIKE '%$third%')"
I'm not certain this is as effective as SQL's REGEXP, but it should work since every part is sectioned out. May not work if a number is like this in the db:1245667890 because you can find 124,456, and 7890, but the number does not match. This answer assumes there will never be a solid number.

Replace Date format in a string provided using regular expression

I am trying to change a string which may have a date inside e.g.
"This is the test string with 22/12/2012. 23/12/12 could anywhere in the string"
I need to change above string so that date are in the format d-m-y i.e.
"This is the test string with 22-12-2012. 23-12-12 could appear anywhere in the string"
EDIT:
Please note that the date will could changed in terms of years i.e. 2012 or 12 could be used at time i.e 20/06/2012, 20/06/12. Only year could be 2 or 4 digits, rest will be same.
Any help will be highly appreciated.
Cheers,
Use preg_replace like this:
$repl = preg_replace('~(\d{2})/(\d{2})/(\d{2,4})~', '$1-$2-$3', $str);
Live Demo: http://ideone.com/7HDNZa
$string = preg_replace("/([0-9]{2})\/([0-9]{2})\/([0-9]{2,4})/", "$1-$2-$3", $string);
The regex will find 3 lots of 2 numbers (or 2x2 + 1x4) separated by /'s and replace them with the same numbers separated by -'s.
You could try something like this:
preg_replace('~\b([0-2]?[1-9]|3[01])/(0?[1-9]|1[0-2])/(?=(?:\d\d|\d{4})\b)~', '$1-$2-', $str);
Should match valid dates only. Does match dates where the prefix 0 is not present, e.g. 4/16/13 if this is not desierable, remove the two first question marks (in [0-2]? and 0?)

substring with last position in php

I want a substring from string in php with starting and last position instead of length.
Since we have function in php substr($str,$start_position,$length);
but I want $last_postion instead of $length because I don't know the length after starting position because it is variable.
e.g $str = october 8, 2012
$str = February 2, 2012
Try using this:
substr($str,$start_position,$last_postion-$start_position);
Well if you don't know the exact length, you need to use strpos first. http://php.net/manual/en/function.strpos.php
You use strpos($the_string, $the_string_to_find) to find the character you're looking for, then you use that returned value in $length for substr.
But as #john said, if you are trying to manipulate a date, or get some value from a date string, it would be a hundred times easier to use strtotime("october 8th, 2012"). You can then format that date however you want, or add / substract from it using a second multiplier.
substr($str, $start_position, $last_postion-$start_position)

Extract date from string in format "DD MMM YYYY"

I am trying to extract a date from a string variable and was hoping to get some help.
$editdate = "Content last modified on 17 May 2011 at 23:13";
from this string, I am trying to extract 17 May 2011, please keep in mind that the date will vary and the code needs to be able to extract any date in this format, DD MMM YYYY.
I thought of using preg_match to do this but I couldn't come up with a proper regex pattern that would extract the date properly.
Is this possible to do with regex or should I use a different function?
Thanks for the help !
Try:
$timestamp = strtotime( str_replace( array("Content last modified ", "at"), "", $editdate ) );
Which will leave you with an epoch time stamp that you can then output however you like using date()
This is possible with a regex. Given the format DD MMM YYYY you would need a regex that matches two (or one?) digits, then one space, three letters, one space and four digits.
That would look like:
$regex = '/(\d{2} [a-z]{3} \d{4})/i';
This can be optimized further.
Presuming the textual content of your string is always the same, and that it always ends with the time...
$editdate = substr($editdate, 25, -9); // 17 May 2011
However, this is very inflexible if the date format were ever to change.
Try this 'un:
preg_match('/(\d?\d [A-Za-z]+ \d\d\d\d) at (\d\d\:\d\d)/', $editdate, $matches);
print_r($matches);
$date = $matches[1];
$time = $matches[2];
I THINK that'll work in all cases (though it is pretty ugly).... :)
This might be the pattern that does the trick:
([0-9]){1}([0-9]){0,1}(\s.*\s)([0-9]){4}
Search for 1 digit then there might be another, followed by a space and character, a space and 4 digits for the year.

PHP/regex: matching/replacing 24-hour times

How can I take a line like this:
Digital Presentation (10:45), (11:30), 12:00, 12:40, 13:20, 14:00, 14:40, 15:20, 16:00, 16:40, 17:20, 18:00, 18:40, 19:20, 20:00, 20:40, 21:20, 22:00, 22:40, 23:10, 23:40.
And match all the 24 hour times so I can convert to a more human readable format using date()?
Also I want to match times in the 24:00-24:59 range too
Thanks!
You could use a regular expression like the following, which allows values from 00:00 through to 24:59 inclusive.
(?:[01][0-9]|2[0-4]):[0-5][0-9]
You seem to know what you're doing, so I'll only give a brief example without converting the times into date strings.
$times = array();
if (preg_match_all('/(?:[01][0-9]|2[0-4]):[0-5][0-9]/', $subject, $matches)) {
$times = $matches[0];
}
print_r($times);
If the subject string has the chance of values like 1234:5678, which would result in false positives with the above regex, then you could wrap the pattern in \b or some other assertion to make sure the time formatted numbers lie on their own.
It's probably easiest to match something like (\d{2}):(\d{2}) (preg syntax), then convert both submatches to an integer and check whether they are in the correct range.
preg_match_all('/([0-2][\d]):(\d{2})/', $string, $matches)
Now $matches[0] array contains all human readable times.
If you wish to print those along with specific date, feed each time through strtotime() function, like this
foreach ($matches[0] as $time) echo date('Y-m-d H:i:s', strtotime($time));

Categories