2012-12-22 255 views
0

我試圖在這裏將文件名拆分爲3部分。PHP - 正則表達式刪除括號之間的字符串

實施例:藝術家 - 標題(混合)或藝術家 - 標題[混合]

我的代碼爲止。

preg_match('/^(.*) - (.*)\.mp3$/', $mp3, $matches); 
$artist = $matches[1]; 
$title = $matches[2]; 
echo "File: $mp3" . "Artist: $artist" . "\n" . "Title: $title" . "<br />"; 

這讓我成爲藝術家和標題。我遇到的問題是Mix在()或[]之間。我不知道如何修改我的正則表達式以捕獲該部分。

+0

你的模式不工作至今。你可能還沒有嘗試過。 – Sithu

+1

我試過這個和它的工作。到目前爲止,我得到o/p作爲藝術家:藝術家標題:標題(混合) – Naveen

回答

1

這不是一個100%的正則表達式的解決方案,但我認爲這是最優雅的,你會得到。

基本上,你要捕獲(anything)[anything],這可以表示爲\(.*\)|\[.*\]。然後,製作一個捕獲組,然後雙重轉義,得到(\\(.*\\)|\\[.*\\])

不幸的是,這也捕獲了()[],所以你必須去掉那些;我只是用substr($matches[3], 1, -1)做的工作:

$mp3 = "Jimmy Cross - I Want My Baby Back (Remix).mp3"; 
preg_match('/^(.*) - (.*) (\\(.*\\)|\\[.*\\])\.mp3$/', $mp3, $matches); 
$artist = $matches[1]; 
$title = $matches[2]; 
$mix = substr($matches[3], 1, -1); 
echo "File: $mp3" . "<br/>" . "Artist: $artist" . "<br/>" . "Title: $title" . "<br />" . "Mix: $mix" . "<br />"; 

打印出:

文件:吉米·克羅斯 - 我希望我的寶貝返回(混音).MP3
藝術家:吉米·克羅斯
標題:我希望我的寶貝回來
混音:混音

+0

這很好。但是,如果我有一個情況,我只有藝術家 - 標題。它失敗。此外,重新混音打印爲(混音)。我會盡力解決這個問題。感謝幫助。 – Naveen

+0

我的不好,我完全錯過了你用來消除()的子串。謝謝你,像一個魅力:) – Naveen

+0

沒問題!祝你好運! :) – Eric

0

嘗試'/^(.*) - ([^\(\[]*) [\(\[] ([^\)\]]*) [\)\]]\.mp3$/'

然而,這未必是這樣做的最有效方式。

+0

Dint工作。我甚至沒有得到藝術家和頭銜。 – Naveen

0

我會使用命名子模式爲這種特定情況。

$mp3s = array(
    "Billy May & His Orchestra - T'Ain't What You Do.mp3", 
    "Shirley Bassey - Love Story [Away Team Mix].mp3", 
    "Björk - Isobel (Portishead remix).mp3", 
    "Queen - Another One Bites the Dust (remix).mp3" 
); 

$pat = '/^(?P<Artist>.+?) - (?P<Title>.*?)(*[\[\(](?P<Mix>.*?)[\]\)])?\.mp3$/'; 

foreach ($mp3s as $mp3) { 
    preg_match($pat,$mp3,$res); 
    foreach ($res as $k => $v) { 
     if (is_numeric($k)) unset($res[$k]); 
     // this is for sanitizing the array for the output 
    } 
    if (!isset($res['Mix'])) $res['Mix'] = NULL; 
    // this is for the missing Mix'es 
    print_r($res); 
} 

將輸出

Array (
    [Artist] => Billy May & His Orchestra 
    [Title] => T'Ain't What You Do 
    [Mix] => 
) 
Array (
    [Artist] => Shirley Bassey 
    [Title] => Love Story 
    [Mix] => Away Team Mix 
) 
Array (
    [Artist] => Björk 
    [Title] => Isobel 
    [Mix] => Portishead remix 
) 
Array (
    [Artist] => Queen 
    [Title] => Another One Bites the Dust 
    [Mix] => remix 
) 
相關問題