Question

I need to parse a string and replace a specific format for tv show names that don't fit my normal format of my media player's queue.

Some examples

Show.Name.2x01.HDTV.x264 should be Show.Name.S02E01.HDTV.x264
Show.Name.10x05.HDTV.XviD should be Show.Name.S10E05.HDTV.XviD

After the show name, there may be 1 or 2 digits before the x, I want the output to always be an S with two digits so add a leading zero if needed. After the x it should always be an E with two digits.

I looked through the manual pages for the preg_replace, split and match functions but couldn't quite figure out what I should do here. I can match the part of the string I want with /\dx\d{2}/ so I was thinking first check if the string has that pattern, then try and figure out how to split the parts out of the match but I didn't get anywhere.

I work best with examples, so if you can point me in the right direction with one that would be great. My only test area right now is a PHP 4 install, so please no PHP 5 specific directions, once I understand whats happening I can probably update it later for PHP 5 if needed :)

Was it helpful?

Solution

A different approach as a solution using #sprintf using PHP4 and below.

$text = preg_replace('/([0-9]{1,2})x([0-9]{2})/ie',
                     'sprintf("S%02dE%02d", $1, $2)', $text);

Note: The use of the e modifier is depreciated as of PHP5.5, so use preg_replace_callback()

$text = preg_replace_callback('/([0-9]{1,2})x([0-9]{2})/', 
      function($m) {
         return sprintf("S%02dE%02d", $m[1], $m[2]);
      }, $text);

Output

Show.Name.S02E01.HDTV.x264
Show.Name.S10E05.HDTV.XviD

See working demo

OTHER TIPS

preg_replace is the function you are looking function.

You have to write a regex pattern that picks correct place.

  <?php
  $replaced_data = preg_replace("~([0-9]{2})x([0-9]{2})~s", "S$1E$2", $data);
  $replaced_data = preg_replace("~S([1-9]{1})E~s", "S0$1E", $replaced_data);
  ?>

Sorry I could not test it but it should work.

An other way using the preg_replace_callback() function:

$subject = <<<'LOD'
Show.Name.2x01.HDTV.x264 should be Show.Name.S02E01.HDTV.x264
Show.Name.10x05.HDTV.XviD should be Show.Name.S10E05.HDTV.XviD
LOD;

$pattern = '~([0-9]++)x([0-9]++)~i';
$callback = function ($match) {
    return sprintf("S%02sE%02s", $match[1], $match[2]);
};

$result = preg_replace_callback($pattern, $callback, $subject);

print_r($result);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top