A
A
Andrej Kopp2020-06-21 23:10:47
PHP
Andrej Kopp, 2020-06-21 23:10:47

How to cut the file name and split into variables through regular expressions?

Hello. At me not absolutely standard task on regexes. I'm a noob in regular seasons, so I'm asking for help. There are file names:


02. Goodwin [Heroes of Comic Books] - Shouting Sirens (freestyle)
12. Stylish Billy feat. aka Ahmed - Chisto e (Stylish Billy prod.)
04.Nuttkase feat. Bird - If Friend (Khasol-Version) (Phunk Masta Seven prod.)
02.Dr.MokRolog,Old Primus,JustSmile,Vine Bi - Elektrograch (Pro100 Beatz prod.)


It is necessary to cut the name from the uploaded file and cut it using regular expressions according to the following scenario:


  1. If the name starts with "01." (numbers and dot, cut them out)
  2. We take the content up to the space and up to the hyphen "-", this is saved in the artist field
  3. We take the content after the hyphen and space "-", store it in the name field
  4. After the name, in most cases there are either brackets "( )" or square brackets "[ ]", and sometimes the brackets are repeated. Is it possible in this variant to add the first closing brackets to the file name, and to take the last ones and insert them into the beatmaker field?!



That is, the output should have

$artist = 'Стильный Билли';
$feat = 'aka Ахмед';
$name = 'Чисто ё';
$beatmaker = 'Стильный Билли';


like this

$artist = 'Nuttkase';
$feat = 'Птаха';
$name = 'Если Друг (Хасол-Версия)';
$beatmaker = 'Phunk Masta Seven';


and like this

$artist = 'Dr.MokRolog';
$feat = 'Old Primus,JustSmile,Vine Bi';
$name = 'Электрограч';
$beatmaker = 'Pro100 Beatz';


I would be grateful if here https://regex101.com/r/AD860D/1 show immediately how it will be cut.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stockholm Syndrome, 2020-06-22
@sequelone

function parseTrack($str) {
    [$first_part, $second_part] = explode(' - ', $str); 
    $first_part = preg_replace('~^\d+\. ?~', '', $first_part); 

    $artists = preg_split('~ feat\. |,~', $first_part);
    $artist = $artists[0];
    $feat = array_slice($artists, 1);

    preg_match('~^(.*?)(?: \(([^(]+) prod\.?\))?$~', $second_part, $match);
    return [
        'artist' => $artist, 
        'feat' => $feat, 
        'name' => $match[1],
        'beatmaker' => isset($match[2]) ? $match[2] : null
    ];
}

D
Dmitry Entelis, 2020-06-21
@DmitriyEntelis

/^([\d]+\.)?\s?([^-]+)\s-\s(.+)\((.+)?\)$/img
seems to be so

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question