2012-12-22 256 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 
) 
相关问题