简体   繁体   中英

How do I rewrite this compress() function to not use a while() loop?

I have the following compress() function:

function compress($input){
   $from = array("\r\n", "\n");
   $to = array('', '');
   $output = str_replace($from, $to, $input);
   while(true){
      $output = str_replace("  ", " ", $output);
      if (strpos($output, "  ") === FALSE){
         break;
      }
   }
   return $output;
}

I'm using it to compress the output HTML code to not contain any linebreaks, nor more than 2 subsequent spaces.

I was wondering whether this would be faster and more optimized if done using regex replace. However, even if it would, I'm not sure how to do it.

Any ideas?

How about:

return preg_replace(
    '# {2,}#',
    '  ',
    preg_replace(
        '#\r?\n#s',
        '',
        $input
    )
);

I believe that will do what you're suggesting, and no more. As for whether it's faster or more efficient, you'd have to run some tests, I can't say offhand. preg_replace is generally relatively expensive. I'm calling it twice here, so there's a fair amount of overhead. But it's an example of how you might do it with p_r.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM