2013-06-24 47 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 
}