开发者

How to extract year using preg_match

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/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜