我正在使用缓冲区清除器,如PHP手动注释中所示,但是在文本区域中出现了双换行符问题。
当从我的数据库中取出包含双/三/四重换行符的字符串并将其放入textarea
时,换行符只会缩减为单个换行符。
因此:函数是否可以排除<pre>
、<textarea>
和</pre>
、</textarea>
之间的所有输出?
看到这个问题,How to minify php html output without removing IE conditional comments?,我想我需要使用preg_match
,但是我不知道如何将它实现到这个函数中。
我使用的功能是
function sanitize_output($buffer) {
$search = array(
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s' // shorten multiple whitespace sequences
);
$replace = array(
'>',
'<',
'\\1'
);
$buffer = preg_replace($search, $replace, $buffer);
return $buffer;
}
ob_start("sanitize_output");
是的,我用这个消毒剂和GZIP
来获得尽可能小的尺寸。
发布于 2015-01-16 18:36:24
以下是在评论中提到的功能的实现:
function sanitize_output($buffer) {
// Searching textarea and pre
preg_match_all('#\<textarea.*\>.*\<\/textarea\>#Uis', $buffer, $foundTxt);
preg_match_all('#\<pre.*\>.*\<\/pre\>#Uis', $buffer, $foundPre);
// replacing both with <textarea>$index</textarea> / <pre>$index</pre>
$buffer = str_replace($foundTxt[0], array_map(function($el){ return '<textarea>'.$el.'</textarea>'; }, array_keys($foundTxt[0])), $buffer);
$buffer = str_replace($foundPre[0], array_map(function($el){ return '<pre>'.$el.'</pre>'; }, array_keys($foundPre[0])), $buffer);
// your stuff
$search = array(
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s' // shorten multiple whitespace sequences
);
$replace = array(
'>',
'<',
'\\1'
);
$buffer = preg_replace($search, $replace, $buffer);
// Replacing back with content
$buffer = str_replace(array_map(function($el){ return '<textarea>'.$el.'</textarea>'; }, array_keys($foundTxt[0])), $foundTxt[0], $buffer);
$buffer = str_replace(array_map(function($el){ return '<pre>'.$el.'</pre>'; }, array_keys($foundPre[0])), $foundPre[0], $buffer);
return $buffer;
}
总是有优化的余地,但这是可行的。
发布于 2015-01-16 18:09:21
对于PRE
,有一个不适用于TEXTAREA
的简单解决方案:在输出值之前,用
替换空格,然后使用nl2br()
替换为BR
元素的换行符。它不雅致,但很实用:
<pre><?php
echo(nl2br(str_replace(' ', ' ', htmlspecialchars($value))));
?></pre>
不幸的是,它不能用于TEXTAREA
,因为浏览器将<br />
显示为文本。
发布于 2015-01-18 15:41:02
function nl2ascii($str){
return str_replace(array("\n","\r"), array(" "," "), $str);
}
$StrTest = "test\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\rtest";
ob_start("sanitize_output");
?>
<textarea><?php echo nl2ascii($StrTest); ?></textarea>
<textarea><?php echo $StrTest; ?></textarea>
<pre style="border: 1px solid red"><?php echo nl2ascii($StrTest); ?></pre>
<pre style="border: 1px solid red"><?php echo $StrTest; ?></pre>
<?php
ob_flush();
原始输出
<textarea>test test</textarea>
<textarea>test
test</textarea>
<pre style="border: 1px solid red">test test</pre>
<pre style="border: 1px solid red">test
test</pre>
视觉输出
https://stackoverflow.com/questions/27878158
复制相似问题