RosettaCodeData/Task/Run-length-encoding/PHP/run-length-encoding.php

19 lines
455 B
PHP
Raw Permalink Normal View History

2013-04-10 23:57:08 -07:00
<?php
2019-09-12 10:33:56 -07:00
function encode($str)
{
return preg_replace_callback('/(.)\1*/', function ($match) {
return strlen($match[0]) . $match[1];
}, $str);
2013-04-10 23:57:08 -07:00
}
2019-09-12 10:33:56 -07:00
function decode($str)
{
return preg_replace_callback('/(\d+)(\D)/', function($match) {
return str_repeat($match[2], $match[1]);
}, $str);
2013-04-10 23:57:08 -07:00
}
2019-09-12 10:33:56 -07:00
echo encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'), PHP_EOL;
echo decode('12W1B12W3B24W1B14W'), PHP_EOL;
2013-04-10 23:57:08 -07:00
?>