我有字符串(在数组中):
$a = "account Tel48201389 user@whatever.net dated 2013-07-01 in JHB".
和
$b = "installation on 2013-08-11 in PE".
我需要仅使用PHP从每个字符串中获取完整日期
是否可以使用带有pregmatch的通配符?
我试过了:
preg_match('/(?P<'name'>\w+): (?P'<'digit-digit-digit'>'\d+)/', $str, $matches);
但它会出错。
最终结果应为:$a = 2013-07-01"
和$b = "2013-08-11"
谢谢!
答案 0 :(得分:1)
您可以使用preg_match_all获取字符串中的所有日期模式。所有字符串匹配都将保存在一个数组中,该数组应作为参数传递给函数。
在此示例中,保存数组$ matches中的所有模式dddd-dd-dd。
$string = "account Tel48201389 user@whatever.net dated 2013-07-01 in JHB installation on 2013-08-11 in PE";
if (preg_match_all("@\d{4}-\d{2}-\d{2}@", $string, $matches)) {
print_r($matches);
}
祝你好运!
答案 1 :(得分:0)
$a = "account Tel48201389 user@whatever.net dated 2013-07-01 in JHB";
if(preg_match('%[0-9]{4}+\-+[0-9]{2}+\-[0-9]{2}%',$a,$match)) {
print_r($match);
}
应该适用于两个字符串 - 如果日期始终采用此格式。
答案 2 :(得分:0)
你可以这样做。
<?php
$b = 'installation on 2013-08-11 in PE';
preg_match('#([0-9]{4}-[0-9]{2}-[0-9]{2})#', $b, $matches);
if (count($matches) == 1) {
$b = $matches[0];
echo $b; # 2013-08-11
}
?>
答案 3 :(得分:0)
试试这个......
$a = "account Tel48201389 user@whatever.net dated 2013-07-01 in JHB";
preg_match("/(?P<year>[0-9]{4})-(?P<month>[0-9]{2})-(?P<day>[0-9]{2})/", $a, $matches);
if($matches){
echo $matches[0];// For the complete string
echo $matches['year'];//for just the year etc
}