2012-10-13 26 views
1

我试图匹配在字符串中找到的所有日期的所有出现,这里是功能匹配一年

$description = "1999 2008 1998"; 

if(preg_match("/[12][0-9]{3}/", $description, $matches)){ 
    print_r($matches); 
} 

的问题是,只有在第一次约会时返回这是1999,我其实想要匹配所有日期。

我应该在正则表达式中改变什么?

+0

如果什么年份是无效像7777 – Baba

+0

@Baba 7777将不会匹配...... –

回答

2

你的意思是?

<?php 
$description = "1999 2008 1998"; 

if(preg_match_all("/[12][0-9]{3}/", $description, $matches)){ 
    print_r($matches); 
} 

唯一的区别是preg_match_all而不是preg_match

+2

这一切的时候,我不知道,有一个preg_match_all,多么尴尬。无论如何感谢 –

+0

这就是你想要的一切吗? – xception

+0

是的,几乎 –

0
<?php 
$description = "1999 2008 1998"; 

$a = Array(preg_match_all('/(\d{4})*/', $description, $matches)); 

$count = count($matches); 

for ($i = 0; $i <= $count + 2; $i++) { 
    echo $matches[0][$i] . "\n"; 
} 
?> 

输出

1999 
2008 
1998