Using php regex to split a string

I have a problem breaking this line into components. An example of a line that I have is - Criminal.Minds.S10E22.WEB-DL.x264-FUM[ettv]. I try to break it down to the following: Criminal Minds, 10, 22.

Although I scolded a bit in perl regex, the php implementation confused me.

I wrote the following:

$word = "Criminal.Minds.S10E22.WEB-DL.x264-FUM[ettv]";
// First replace periods and dashes by spaces
$patterns = array();
$patterns[0] = '/\./';
$patterns[1] = '/-/';
$replacement = ' ';
$word = preg_replace($patterns, $replacement, $word);
print_r(preg_split('#([a-zA-Z])+\sS(\d+)E(\d+)#i', $word));

What exits Array ( [0] => Criminal [1] => WEB DL x264 FUM[ettv] ) Please point me in the right direction.

+4
source share
1 answer

Use match rather than split if the string is always in this format:

$word = "Criminal.Minds.S10E22.WEB-DL.x264-FUM[ettv]";
preg_match('~^(?<name>.*?)\.S(?<season>\d+)E(?<episode>\d+)~', $word, $m);
print_r($m);

See PHP demo

You can then access the values name, seasonand episode, using $m["name"], $m["season"]and $m["episode"].

:

  • ^ -
  • (?<name>.*?) - , 0+, , , ....
  • \.S - .S
  • (?<season>\d+) - "", , 1 +
  • E - char E
  • (?<episode>\d+) - "", , 1 +
+3

Source: https://habr.com/ru/post/1665858/


All Articles