2014-02-05 149 views
0

我有了從谷歌日曆JSON日期,我需要找回的具體日期,YYY-MM-DD格式的字符串:篩選日期

"content": { 
    "$t": "When: Mon Jun 30, 2014 to Mon Jul 7, 2014 \n\u003cbr /\u003e\n\n\n\u003cbr /\u003eEvent Status: confirmed", 
    "type": "html" 
}, 

我想過做一個函數來「乾淨」的使用分裂,是這樣的:

$string = "When: Mon Jun 30, 2014 to Mon Jul 7, 2014 \n\u003cbr /\u003e\n\n\n\u003cbr /\u003eEvent Status: confirmed"; 
$splitOne = split(' to ',$string); 
$firstDate = split('When: ', $splitOne[0]); 
$secondtDate = split(' \n', $splitOne[1]); 
echo $firstDate[1]; echo '<br />'; 
echo $secondtDate[0]; echo '<br />'; 

但這呼應:

Mon Jun 30, 2014 // as expected 
Mon Jul 7, 2014 \u003cbr /\u003e \u003cbr /\u003eEvent Status: confirmed // not expected, should be "Mon Jul 7, 2014" 

我在想什麼在split()?順便說一句,有沒有正則表達式的解決方案呢?

+0

你應該做一個'的var_dump($ splitOne [1]); ',也許'\ n'之前的字符不是空格。你也可以用'\ n'爆炸並修剪結果。 – jeroen

+0

@jeroen,var_dump給了'string(75)「Mon Jul 7,2014 \ u003cbr/\ u003e \ u003cbr/\ u003eEvent狀態:確認」' – Rikard

+0

沒有'\ n'這樣也沒有解決方案,也沒有解決方案尋找'\ n'正在工作...... – jeroen

回答

2

可能更容易,只需使用一個正則表達式:

$string = "When: Mon Jun 30, 2014 to Mon Jul 7, 2014 \n\u003cbr /\u003e\n\n\n\u003cbr /\u003eEvent Status: confirmed"; 

preg_match('/When: (.*) to ([^\n]+)/', $string, $matches); 

print_r($matches); 

然後trim()$matches [1],如果需要,[2]。

+0

謝謝,這工作得很好! – Rikard

2

有一個正則表達式的解決方案。我爲你推出了一個正則表達式here

您可以使用捕獲組1-6來提取所需的信息並將其轉換爲您所需的格式。

的正則表達式是:

(?:When:\s[a-zA-Z]{3}\s([a-zA-Z]{3})\s(\d\d?)\,\s(\d{4})\sto\s[a-zA-Z]{3}\s([a-zA-Z]{3})\s(\d\d?)\,\s(\d{4})).* 

與捕獲組:

\1 = Jun 
\2 = 30 
\3 = 2014 
\4 = Jul 
\5 = 7 
\6 = 2014 

PHP代碼示例:

$re = '/(?:When:\s[a-zA-Z]{3}\s([a-zA-Z]{3})\s(\d\d?)\,\s(\d{4})\sto\s[a-zA-Z]{3}\s([a-zA-Z]{3})\s(\d\d?)\,\s(\d{4})).*/'; 
$str = 'When: Mon Jun 30, 2014 to Mon Jul 7, 2014 \n\u003cbr /\u003e\n\n\n\u003cbr /\u003eEvent Status: confirmed'; 

preg_match($re, $str, $matches); 
+0

+1爲__ [regex101](http://regex101.com/r/uW7oH2)__鏈接 – Sergio