2013-06-24 37 views
0

拍摄日期句话我有字符串(数组中的):从字符串PHP

$a = "account Tel48201389 [email protected] 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" 谢谢!

+2

“它给出了一个错误” ......你愿意分享你的错误? – arkascha

+2

我希望你不要像你在这里发布一样写你的代码。 (我的意思是可读性) – GGio

+0

现在你有数组还是你有两个变量'$ a'和'$ b'? – arkascha

回答

1

您可以使用preg_match_all来获取字符串中的所有日期模式。所有字符串匹配都将保存在一个数组中,该数组应该作为参数传递给该函数。

在此示例中,将所有模式dddd-dd-dd保存在数组$ matches中。

$string = "account Tel48201389 [email protected] 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); 
} 

祝你好运!

+0

哇,这看起来很酷。谢谢。 echo $ matches [0] [0]。 “,”。 $匹配[0] [1]。 “\ n” 个; – KarlosFontana

0
$a = "account Tel48201389 [email protected] dated 2013-07-01 in JHB"; 

    if(preg_match('%[0-9]{4}+\-+[0-9]{2}+\-[0-9]{2}%',$a,$match)) { 

    print_r($match);  

    } 

应该对两个字符串都适用 - 如果日期总是采用这种格式。

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 
} 
?> 
0

试试这个....

$a = "account Tel48201389 [email protected] 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 
}