2017-03-22 62 views
0

所以我有一塊文本,我希望將其轉換爲PHP數組。最終目標是儘快將超過40年的數據輸入MySQL數據庫。將格式化文本塊轉換爲PHP數組

(1) FRANK SINATRA – Strangers In The Night (and charts) 
(4) THE MERSEYS – Sorrow 
(19) PAUL & BARRY RYAN – I Love Her 
(NEW) EDDY ARNOLD – I Want To Go With You 

所以理想情況下,如果數據可以被解析成下列數組,那麼我可以處理數據。任何想法如何做到這一點?我確實想過使用preg_split。有沒有其他人有任何想法?

$chartpos[] = "1" 
$artist[] = "FRANK SINATRA" 
$track[] = "Strangers In The Night" 
$performancetype[] = "and charts"` 
+1

使用'preg_match_all()'。 – Barmar

+1

許多歌曲標題包含括號。您將很難區分屬於標題的括號和保持性能類型的括號。 – Barmar

回答

1

這個正則表達式將讓你在$數組有「身份證」元素,包含所有相應的位置上,如果「名」元素相匹配我正確理解您的格式

$a = "(1) FRANK SINATRA – Strangers In The Night (and charts) 
(4) THE MERSEYS – Sorrow 
(19) PAUL & BARRY RYAN – I Love Her 
(NEW) EDDY ARNOLD – I Want To Go With You"; 

preg_match_all('/\((?<id>[0-9]|NEW)\) (?<name>.*)/', $a, $matches); 
print_r($matches); 
0

這將幫助你......

$re = '/\(([0-9NEW]+)\)\s+([A-Z& ]+) – (.*)/m'; 
$str = '(1) FRANK SINATRA – Strangers In The Night (and charts) 
(4) THE MERSEYS – Sorrow 
(19) PAUL & BARRY RYAN – I Love Her 
(NEW) EDDY ARNOLD – I Want To Go With You'; 

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0); 

// Print the entire match result 
var_dump($matches);