note 74899 added to function.php-strip-whitespace
| From: | nyctimus at yahoo dot com | Date: | Thu, 03 May 2007 09:01:52 +0000 |
| Subject: | note 74899 added to function.php-strip-whitespace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-126132@lists.php.net to get a copy of this message | ||
Here's one for CSS:
<?php
function css_strip_whitespace($css)
{
$replace = array(
"#/\*.*?\*/#s" => "", // Strip C style comments.
"#\s\s+#" => " ", // Strip excess whitespace.
);
$search = array_keys($replace);
$css = preg_replace($search, $replace, $css);
$replace = array(
": " => ":",
"; " => ";",
" {" => "{",
" }" => "}",
", " => ",",
"{ " => "{",
";}" => "}", // Strip optional semicolons.
",\n" => ",", // Don't wrap multiple selectors.
"\n}" => "}", // Don't wrap closing braces.
"} " => "}\n", // Put each rule on it's own line.
);
$search = array_keys($replace);
$css = str_replace($search, $replace, $css);
return trim($css);
}
?>
A word on the first regular expression, since it took me a while.
It strips C style comments. /* Like this. */
#/\*.*?\*/#s
^ ^
The pound signs at either end quote the regex. They don't match anything.
#/\*.*?\*/#s
^
The s at the very end sets the PCRE_DOTALL modifier. More info here:
http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php
# /\* .*? \*/ #s
1 2 3
The expression itself consists of 3 parts:
1. the opening comment sequence, represented by /\*
2. everything in the middle, represented by .*?
3. and the closing comment sequence, represented by \*/
#/\*.*?\*/#s
^ ^
The comment asterisks are escaped. If I had used the more common / for PCRE quoting I would've
had to escape those too.
#/\*.*?\*/#s
^
The ? prevents the regex from being greedy. See halfway down this page:
http://www.php.net/manual/en/reference.pcre.pattern.syntax.php
----
Server IP: 69.147.83.197
Probable Submitter: 75.17.63.133
----
Manual Page -- http://www.php.net/manual/en/function.php-strip-whitespace.php
Edit -- https://master.php.net/note/edit/74899
Del: integrated -- https://master.php.net/note/delete/74899/integrated
Del: useless -- https://master.php.net/note/delete/74899/useless
Del: bad code -- https://master.php.net/note/delete/74899/bad+code
Del: spam -- https://master.php.net/note/delete/74899/spam
Del: non-english -- https://master.php.net/note/delete/74899/non-english
Del: in docs -- https://master.php.net/note/delete/74899/in+docs
Del: other reasons-- https://master.php.net/note/delete/74899
Reject -- https://master.php.net/note/reject/74899
Search -- https://master.php.net/manage/user-notes.php