Php WP HTML缩小类不工作
我在电脑上找到了这个脚本。它应该缩小(而不是像类名建议的那样压缩)HTML:Php WP HTML缩小类不工作,php,regex,wordpress,minify,Php,Regex,Wordpress,Minify,我在电脑上找到了这个脚本。它应该缩小(而不是像类名建议的那样压缩)HTML: 自定义方法怎么样 public static function html_compress($buffer) { $chunks = preg_split( '/(<pre.*?\/pre>)/ms', $buffer, -1, PREG_SPLIT_DELIM_CAPTURE ); $buffer = ''; $replace = array( '#[\n\r\t\
自定义方法怎么样
public static function html_compress($buffer)
{
$chunks = preg_split( '/(<pre.*?\/pre>)/ms', $buffer, -1, PREG_SPLIT_DELIM_CAPTURE );
$buffer = '';
$replace = array(
'#[\n\r\t\s]+#' => ' ', // remove new lines & tabs
'#>\s{2,}<#' => '><', // remove inter-tag whitespace
'#\/\*.*?\*\/#i' => '', // remove CSS & JS comments
'#<!--(?![\[>]).*?-->#si' => '', // strip comments, but leave IF IE (<!--[...]) and "<!-->""
'#\s+<(html|head|meta|style|/style|title|script|/script|/body|/html|/ul|/ol|li)#' => '<$1', // before those elements, whitespace is dumb, so kick it out!!
'#\s+(/?)>#' => '$1>', // just before the closing of " >"|" />"
'#class="\s+#'=> 'class="', // at times, there is whitespace before class=" className"
'#(script|style)>\s+#' => '$1>', // <script> var after_tag_has_whitespace = 'nonsens';
);
$search = array_keys($replace);
foreach ( $chunks as $c )
{
if ( strpos( $c, '<pre' ) !== 0 )
{
$c = preg_replace($search, $replace, $c);
}
$buffer .= $c;
}
return $buffer;
}
公共静态函数html\u compress($buffer)
{
$chunks=preg_split('/()/ms',$buffer,-1,preg_split_DELIM_CAPTURE);
$buffer='';
$replace=数组(
'#[\n\r\t\s]+#'=>'',//删除新行和制表符
“#>\s{2,}#si'=>'',//删除注释,但如果IE(“'
“#\s+”,//就在“>”|“/>结束之前
“#class=”\s+#“=>”class=“”,//有时,class=”className“前面有空格
“#(script | style)>\s+#”=>“$1>”,//标记后的变量有“\u空格='nonsens'”;
);
$search=array\u key($replace);
foreach($c块)
{
如果(strpos,$c,这里还有其他问题
我将这个“类”简化为一个单页PHP脚本(将任何$this->调用替换为true(对于IVAR)或静态函数调用)
然后,我使用长HTML输入运行了各种测试,并尝试使用条件注释进行处理,包括复制粘贴之前的条件标记。每次结果都是一行输出
总之,有一些可能性:
在你的HTML中还有其他东西把它扔了(链接到实际页面?)
缩小是在添加额外HTML之前发生的(很可能)
其中一个IVAR不正确(不太可能)
有东西正在将
插入文档的该部分
为什么不在minifyHTML($html)方法的开头插入error_log($html);
(或类似内容)以查看原始html的外观。我猜,这样做的结果会告诉您它不起作用的原因。(我猜,您也可以返回$html;
)
编辑---
这是我的“脚本”,请注意,保留了条件注释,剥离了非条件HTML注释。我根本不关心行格式,因为这只是您提供的原始类中的一个黑客作业
<?php
$html = <<<EOF
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--[if lt IE 7 ]><html class="ie ie6" lang="en"><![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"><![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"><![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html lang="en"><!--<![endif]-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Page Title</title>
<meta name="description" content="desc" />
<meta name="keywords" content="c" />
<meta name="robots" content="INDEX,FOLLOW" />
<link rel="icon" href="http://www.stackoverflow.com/" type="image/x-icon" />
<link rel="shortcut icon" href="http://www.stackoverflow.com/" type="image/x-icon" />
<!--[if lt IE 7]>
<script type="text/javascript">
//<![CDATA[
var BLANK_URL = '';
//]]>
</script>
<![endif]-->
<!--[if lt IE 8]>
<style type="text/css">
.single-call-to-action .action-text {
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#66000000, endColorstr=#66000000);
}
#PaypalSideBar a img {
left: 0 !important;
top: 0 !important;
width: 182px !important;
height: 96px !important;
}
</style>
<![endif]-->
<!--[if lt IE 9]>
<style type="text/css">
.single-call-to-action .action-text {
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#66000000, endColorstr=#66000000)";
}
</style>
<![endif]-->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">jQuery.noConflict();</script>
<link href="//fonts.googleapis.com/css?family=Marck+Script" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="http://www.stackoverflow.com/test.css" media="all" />
<!--[if lt IE 8]><link rel="stylesheet" type="text/css" href="http://www.stackoverflow.com/test.css" media="all" /><![endif]-->
<!--[if lt IE 7]><script type="text/javascript" src="http://www.stackoverflow.com/test.js"></script><script type="text/javascript" src="http://www.stackoverflow.com/test.js"></script><![endif]-->
<script type="text/javascript">
//<![CDATA[
Mage.Cookies.path = '/';
//]]>
</script>
<script type="text/javascript">
//<![CDATA[
optionalZipCountries = ["US"];
//]]>
</script>
<!-- BEGIN GOOGLE ANALYTICS CODEs -->
<script type="text/javascript">
//<![CDATA[
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-x']);
_gaq.push(['_setDomainName', 'http://www.stackoverflow.com/']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
//]]>
</script>
<!-- END GOOGLE ANALYTICS CODE -->
<script type="text/javascript">
//<![CDATA[
window.HDUSeed = 'x';
window.HDUSeedIntId = setInterval(function() {
if (document.observe) {
document.observe('dom:loaded', function() {
for (var i = 0; i < document.forms.length; i++) {
if (document.forms[i].getAttribute('action') && document.forms[i].getAttribute('action').match('contacts/index/post')) {
var el = document.createElement('input');
el.type = ('hidden');
el.name = 'hdu_seed';
el.value = window.HDUSeed;
document.forms[i].appendChild(el);
}
}
});
clearInterval(window.HDUSeedIntId)
}
}, 100)
//]]>
</script>
<script type="text/javascript">//<![CDATA[
var Translator = new Translate([]);
//]]></script><meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
<style type="text/css">
/*default iteaser*/
#TT2ILTbox {
background-color: #f3f3f3;
border: 1px solid #d2d2d2;
padding: 10px;
text-align: center;
width: 280px;
margin-bottom: 10px;
margin-top: 10px;
}
#TT2ILTbox h2 {
font-size: 12px;
font-weight: bold;
margin: 5px 0 5px 0;
}
#TT2ILTcount-line * {
font-size: 11px;
}
#TT2ILTcount-line strong {
font: bold 11px Arial;
}
#TT2ILTcount-line p {
margin: 5px 0 5px 0;
}
#TT2ILTbutton-holder {
display: -moz-box !important;
display: block;
height: 31px;
text-align: center;
}
a.TT2ILTbutton, a.TT2ILTbutton span {
background-color: #fa002f;
}
.TT2ILTbutton * {
font: bold 12px Arial;
}
a.TT2ILTbutton {
background-image: url('http://static.www.turnto.com/tra2/images/iteaser/1/button-right.png');
background-repeat: no-repeat;
background-position: top right;
display: block;
height: 31px;
margin-right: 6px;
padding-right: 16px;
text-decoration: none;
color: white;
}
a.TT2ILTbutton span {
background-image: url('http://static.www.turnto.com/tra2/images/iteaser/1/button-left.png');
background-repeat: no-repeat;
display: block;
line-height: 22px;
padding: 2px 0 7px 18px;
}
a.TurnToIteaSee {
font-size: 11px;
text-decoration: none;
color: #000;
cursor: pointer;
}
</style>
</head>
<body class=" cms-index-index cms-home">
<div class="wrapper">
<noscript>
<div class="global-site-notice noscript">
<div class="notice-inner">
<p>
<strong>JavaScript seems to be disabled in your browser.</strong><br />
You must have JavaScript enabled in your browser to utilize the functionality of this website. </p>
</div>
</div>
</noscript>
<div class="page">
</div>
</div>
</body>
</html>
EOF;
function removeWhiteSpace($str)
{
$str = str_replace("\t", ' ', $str);
$str = str_replace("\n", '', $str);
$str = str_replace("\r", '', $str);
while (stristr($str, ' '))
{
$str = str_replace(' ', ' ', $str);
}
return $str;
}
$pattern = '/<(?<script>script).*?<\/script\s*>|<(?<style>style).*?<\/style\s*>|<!(?<comment>--).*?-->|<(?<tag>[\/\w.:-]*)(?:".*?"|\'.*?\'|[^\'">]+)*>|(?<text>((<[^!\/\w.:-])?[^<]*)+)|/si';
preg_match_all($pattern, $html, $matches, PREG_SET_ORDER);
$overriding = false;
$raw_tag = false;
// Variable reused for output
$html = '';
foreach ($matches as $token)
{
$tag = (isset($token['tag'])) ? strtolower($token['tag']) : null;
$content = $token[0];
if (is_null($tag))
{
if ( !empty($token['script']) )
{
$strip = true;
}
else if ( !empty($token['style']) )
{
$strip = true;
}
else if ($content == '<!--wp-html-compression no compression-->')
{
$overriding = !$overriding;
// Don't print the comment
continue;
}
else if (true)
{
if (!$overriding && $raw_tag != 'textarea')
{
// Remove any HTML comments, except MSIE conditional comments
$content = preg_replace('/<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->).)*-->/s', '', $content);
}
}
}
else
{
if ($tag == 'pre' || $tag == 'textarea')
{
$raw_tag = $tag;
}
else if ($tag == '/pre' || $tag == '/textarea')
{
$raw_tag = false;
}
else
{
if ($raw_tag || $overriding)
{
$strip = false;
}
else
{
$strip = true;
// Remove any empty attributes, except:
// action, alt, content, src
$content = preg_replace('/(\s+)(\w++(?<!\baction|\balt|\bcontent|\bsrc)="")/', '$1', $content);
// Remove any space before the end of self-closing XHTML tags
// JavaScript excluded
$content = str_replace(' />', '/>', $content);
}
}
}
if ($strip)
{
$content = removeWhiteSpace($content);
}
$html .= $content;
}
echo $html;
该网站只是将代码重新命名。不知何故,使用“他们的”代码比使用实际的插件要好?哦,好吧
WordPress和标准PHP都有更新版本:
你实际上是如何使用缩小函数/方法的?是的。IE条件没有缩小。你误解了我。你在哪里调用函数,你的html是什么?WP钩子处理调用。在任何情况下,你都不需要依赖钩子。只需实例化类并传递未经缩小的html。嗯……你的目标是什么未统一的HTML?这与类所做的非常相似。此脚本的源代码是什么?是否有针对它的单元测试?我已经使用了两年。还没有单元测试。源代码是internet和我自己的正则表达式熟练程度。我创建了一个脚本,您可能会问为什么要替换。[\n\r\t\s]+#
只有一个空格?为什么\s{2,}有时候你会有类似于hello world
的东西,所以当你删除空格时,你会得到helloworld
。因此在关闭
后留下一个空格。用一个空格替换回车、制表符和空格可以确保如果你用回车和制表符格式化代码(这确实会导致显示空格)您找不到上面的示例。希望这能澄清一点。欢迎您改进它!:)您的示例hello world
不适用于我询问的任何正则表达式。您关于“输入、制表符和空白带一个空格”的解释对我来说没有意义;为什么不再次替换为空字符串呢?当然,但这将是一个很大的问题,因为我在测试中已经完成了。嗨,史蒂文,你是脚本的原始作者吗?是的,我还在维护它。
public static function html_compress($buffer)
{
$chunks = preg_split( '/(<pre.*?\/pre>)/ms', $buffer, -1, PREG_SPLIT_DELIM_CAPTURE );
$buffer = '';
$replace = array(
'#[\n\r\t\s]+#' => ' ', // remove new lines & tabs
'#>\s{2,}<#' => '><', // remove inter-tag whitespace
'#\/\*.*?\*\/#i' => '', // remove CSS & JS comments
'#<!--(?![\[>]).*?-->#si' => '', // strip comments, but leave IF IE (<!--[...]) and "<!-->""
'#\s+<(html|head|meta|style|/style|title|script|/script|/body|/html|/ul|/ol|li)#' => '<$1', // before those elements, whitespace is dumb, so kick it out!!
'#\s+(/?)>#' => '$1>', // just before the closing of " >"|" />"
'#class="\s+#'=> 'class="', // at times, there is whitespace before class=" className"
'#(script|style)>\s+#' => '$1>', // <script> var after_tag_has_whitespace = 'nonsens';
);
$search = array_keys($replace);
foreach ( $chunks as $c )
{
if ( strpos( $c, '<pre' ) !== 0 )
{
$c = preg_replace($search, $replace, $c);
}
$buffer .= $c;
}
return $buffer;
}
<?php
$html = <<<EOF
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--[if lt IE 7 ]><html class="ie ie6" lang="en"><![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"><![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"><![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html lang="en"><!--<![endif]-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Page Title</title>
<meta name="description" content="desc" />
<meta name="keywords" content="c" />
<meta name="robots" content="INDEX,FOLLOW" />
<link rel="icon" href="http://www.stackoverflow.com/" type="image/x-icon" />
<link rel="shortcut icon" href="http://www.stackoverflow.com/" type="image/x-icon" />
<!--[if lt IE 7]>
<script type="text/javascript">
//<![CDATA[
var BLANK_URL = '';
//]]>
</script>
<![endif]-->
<!--[if lt IE 8]>
<style type="text/css">
.single-call-to-action .action-text {
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#66000000, endColorstr=#66000000);
}
#PaypalSideBar a img {
left: 0 !important;
top: 0 !important;
width: 182px !important;
height: 96px !important;
}
</style>
<![endif]-->
<!--[if lt IE 9]>
<style type="text/css">
.single-call-to-action .action-text {
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#66000000, endColorstr=#66000000)";
}
</style>
<![endif]-->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">jQuery.noConflict();</script>
<link href="//fonts.googleapis.com/css?family=Marck+Script" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="http://www.stackoverflow.com/test.css" media="all" />
<!--[if lt IE 8]><link rel="stylesheet" type="text/css" href="http://www.stackoverflow.com/test.css" media="all" /><![endif]-->
<!--[if lt IE 7]><script type="text/javascript" src="http://www.stackoverflow.com/test.js"></script><script type="text/javascript" src="http://www.stackoverflow.com/test.js"></script><![endif]-->
<script type="text/javascript">
//<![CDATA[
Mage.Cookies.path = '/';
//]]>
</script>
<script type="text/javascript">
//<![CDATA[
optionalZipCountries = ["US"];
//]]>
</script>
<!-- BEGIN GOOGLE ANALYTICS CODEs -->
<script type="text/javascript">
//<![CDATA[
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-x']);
_gaq.push(['_setDomainName', 'http://www.stackoverflow.com/']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
//]]>
</script>
<!-- END GOOGLE ANALYTICS CODE -->
<script type="text/javascript">
//<![CDATA[
window.HDUSeed = 'x';
window.HDUSeedIntId = setInterval(function() {
if (document.observe) {
document.observe('dom:loaded', function() {
for (var i = 0; i < document.forms.length; i++) {
if (document.forms[i].getAttribute('action') && document.forms[i].getAttribute('action').match('contacts/index/post')) {
var el = document.createElement('input');
el.type = ('hidden');
el.name = 'hdu_seed';
el.value = window.HDUSeed;
document.forms[i].appendChild(el);
}
}
});
clearInterval(window.HDUSeedIntId)
}
}, 100)
//]]>
</script>
<script type="text/javascript">//<![CDATA[
var Translator = new Translate([]);
//]]></script><meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
<style type="text/css">
/*default iteaser*/
#TT2ILTbox {
background-color: #f3f3f3;
border: 1px solid #d2d2d2;
padding: 10px;
text-align: center;
width: 280px;
margin-bottom: 10px;
margin-top: 10px;
}
#TT2ILTbox h2 {
font-size: 12px;
font-weight: bold;
margin: 5px 0 5px 0;
}
#TT2ILTcount-line * {
font-size: 11px;
}
#TT2ILTcount-line strong {
font: bold 11px Arial;
}
#TT2ILTcount-line p {
margin: 5px 0 5px 0;
}
#TT2ILTbutton-holder {
display: -moz-box !important;
display: block;
height: 31px;
text-align: center;
}
a.TT2ILTbutton, a.TT2ILTbutton span {
background-color: #fa002f;
}
.TT2ILTbutton * {
font: bold 12px Arial;
}
a.TT2ILTbutton {
background-image: url('http://static.www.turnto.com/tra2/images/iteaser/1/button-right.png');
background-repeat: no-repeat;
background-position: top right;
display: block;
height: 31px;
margin-right: 6px;
padding-right: 16px;
text-decoration: none;
color: white;
}
a.TT2ILTbutton span {
background-image: url('http://static.www.turnto.com/tra2/images/iteaser/1/button-left.png');
background-repeat: no-repeat;
display: block;
line-height: 22px;
padding: 2px 0 7px 18px;
}
a.TurnToIteaSee {
font-size: 11px;
text-decoration: none;
color: #000;
cursor: pointer;
}
</style>
</head>
<body class=" cms-index-index cms-home">
<div class="wrapper">
<noscript>
<div class="global-site-notice noscript">
<div class="notice-inner">
<p>
<strong>JavaScript seems to be disabled in your browser.</strong><br />
You must have JavaScript enabled in your browser to utilize the functionality of this website. </p>
</div>
</div>
</noscript>
<div class="page">
</div>
</div>
</body>
</html>
EOF;
function removeWhiteSpace($str)
{
$str = str_replace("\t", ' ', $str);
$str = str_replace("\n", '', $str);
$str = str_replace("\r", '', $str);
while (stristr($str, ' '))
{
$str = str_replace(' ', ' ', $str);
}
return $str;
}
$pattern = '/<(?<script>script).*?<\/script\s*>|<(?<style>style).*?<\/style\s*>|<!(?<comment>--).*?-->|<(?<tag>[\/\w.:-]*)(?:".*?"|\'.*?\'|[^\'">]+)*>|(?<text>((<[^!\/\w.:-])?[^<]*)+)|/si';
preg_match_all($pattern, $html, $matches, PREG_SET_ORDER);
$overriding = false;
$raw_tag = false;
// Variable reused for output
$html = '';
foreach ($matches as $token)
{
$tag = (isset($token['tag'])) ? strtolower($token['tag']) : null;
$content = $token[0];
if (is_null($tag))
{
if ( !empty($token['script']) )
{
$strip = true;
}
else if ( !empty($token['style']) )
{
$strip = true;
}
else if ($content == '<!--wp-html-compression no compression-->')
{
$overriding = !$overriding;
// Don't print the comment
continue;
}
else if (true)
{
if (!$overriding && $raw_tag != 'textarea')
{
// Remove any HTML comments, except MSIE conditional comments
$content = preg_replace('/<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->).)*-->/s', '', $content);
}
}
}
else
{
if ($tag == 'pre' || $tag == 'textarea')
{
$raw_tag = $tag;
}
else if ($tag == '/pre' || $tag == '/textarea')
{
$raw_tag = false;
}
else
{
if ($raw_tag || $overriding)
{
$strip = false;
}
else
{
$strip = true;
// Remove any empty attributes, except:
// action, alt, content, src
$content = preg_replace('/(\s+)(\w++(?<!\baction|\balt|\bcontent|\bsrc)="")/', '$1', $content);
// Remove any space before the end of self-closing XHTML tags
// JavaScript excluded
$content = str_replace(' />', '/>', $content);
}
}
}
if ($strip)
{
$content = removeWhiteSpace($content);
}
$html .= $content;
}
echo $html;