2010-12-02 70 views
0

我有用户输入详细信息的textarea,我想从textarea中提取年份。问题是用户以不同的方式进入年份。如何使用preg_match提取年份

某些用户输入日期为1999'99september 99。我如何使用一个正则表达式字符串来提取年份。

+1

......他们都没有任何机会也进入日,月在同`textarea`? – 2010-12-02 13:01:00

+0

@tim肯定没有日子。有些则使用sep'99或99年9月的月份。 – 2010-12-02 13:08:06

回答

2

这应该用于提取所提到的日期工作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); 

这次来到我的脑海里,太(它为用户提供多一点自由):

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); 

的所有当多个表达式解析上面会更容易些。你为什么需要一个?

如果你只是想解析一个字符串,只包含这个,你应该使用PHP的strtotime()-function

0
\b\d\d(?:\d\d)?\b 

将匹配一个两位或四位数字。所以如果你的字符串只包含年份数字,那应该就够了。

if (preg_match('/\b\d\d(?:\d\d)?\b/', $subject, $regs)) { 
    $result = $regs[0]; 
} 
0

你可以尝试使用strtotime

的strtotime - 解析任何英文文本的日期时间描述为Unix时间戳

date('Y', strtotime($userinput)); 
0
[. -]((?:\d\d|')\d\d)$ 
0

提取只能从字符串的数字:

/\b(\d+)\b/