Search code examples
phparraysglobalpreg-replace-callback

preg_replace_callback store match in global array and replace


I'm trying to compress an HTML code, but keep the style, script, pre and conditional IE untouched.

My problem is that I can't store the matches of function inside an array. I can succesfully replace the regex results, but the resulting array is empty $idarray:

function html_compress($string){

    //Substitute style, script and pre tag with unique id

    $idarray=array();

    $search=array('@<!--\[if\s(?:[^<]+|<(?!!\[endif\]-->))*<!\[endif\]-->@','@<script[^>]*>(?:[^<]+|)</script>@','@<style[^>]*>(?:[^<]+|)</style>@','@<pre[^>]*>(?:[^<]+|)</pre>@','@//<!\[CDATA\[(?:[^<]+|)//]]>@');
    $string=preg_replace_callback($search,
                                  function($m){
                                      $id=uniqid();
                                      global $idarray;
                                      $idarray[]=array($id,$m);
                                      return '<!['.$id.']!>';
                                  },
                                  $string
    );

    $search = array('/\>[^\S ]+/s','/[^\S ]+\</s','/(\s)+/s');
    $replace = array('>','<','\\1');
    $string = preg_replace($search, $replace, $string);

    //Remove blank lines
    $string=preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $string);

    //Replace unique id with script, style, pre original tag
    $c=count($idarray);
    for($i=0;$i<$c;$i++){
        $string = str_replace($idarray[$i][0], $idarray[$i][1], $string);
    }

    Mage::log(print_r($idarray, true), null, 'idarray.log');

    return $string;
}

Solution

  • Ok, at the beginning:

    global $idarray;
    $idarray=array();