5

All of the PHP minify functions I've seen have dealt with physical JavaScript, HTML, CSS files. I would like a function that, when given something like this:

$code = "<html>
    <body>";

Will minify it to one line. I am not looking for something like the YUI Compressor, as that deals with files on a server. I would simply like a function that minifies a string passed to it. Does this exist anywhere?

3
  • You should be able to mock a file using the SPL. Put the string into the file. Pass it the the known minify functions. Commented Jul 10, 2013 at 16:29
  • That sounds pretty inefficient though. Is there a straight-up function that does it? Commented Jul 10, 2013 at 16:50
  • Maybe, Maybe not. The SPL has a mock file, that you can put n memory. I'm not sure how inefficient it is. see; php.net/manual/en/spltempfileobject.construct.php Commented Jul 10, 2013 at 17:01

3 Answers 3

9

You may be looking for:

$code = "<html>
    <body>";

echo str_replace(array("\r", "\n"), '', $code);
Sign up to request clarification or add additional context in comments.

9 Comments

Well, I'm looking for a complete minification function, so you could pass, say, the front-end source code for Google to it.
And it would do what? Fetch all the assets (e.g. external JS/CSS/images etc) and inline/minify them? What are you trying to do? developers.google.com/speed/pagespeed/module might be a good tool to solve whatever it is you are doing?
I simply would like to have a function that minifies a STRING of HTML/CSS/JS, not a FILE
How is it any different? The code will read the file into a string, minify the string, then write back to the file. github.com/mrclay/minify/tree/master/min/lib is the code for PHP Minify - you'll see the functions needed in there.
I actually ended up using the JSMin.php file; thanks for the help!
|
0

I never tried these ones, but I came across them once:

For JavaScript and CSS:

http://castlesblog.com/2010/august/14/php-javascript-css-minification

2 Comments

Thanks for the answer, but this is for external files, not strings.
The link is broken: "It looks like the page your are looking for is missing. Please check the address or try another page."
0

This one worked for me:

$out = file_get_contents(__DIR__ . '/page.html');
$replace = ["\r", "\t", "\n"];
for ($i = 2; $i <= 50; $i++) {
    $replace[] = str_repeat(' ', $i);
}
file_put_contents(__DIR__ . '/page.html', str_replace($replace, '', $out));

and more easy with regex

$out = file_get_contents(__DIR__ . '/page.html');
file_put_contents(__DIR__ . '/output.html', preg_replace("/(\s{2,}|\t|\r|\n)/i",'',$out));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.