[thinkphp去掉html中的空格和换行的方法]ThinkPHP去掉html中的空格和换行的方法

更新时间:2019-12-07    来源:thinkphp    手机版     字体:

【www.bbyears.com--thinkphp】

thinkphp3.2.2中有无法删除模板中的空格和换行的问题:

即使配置了 'TMPL_STRIP_SPACE' => true 也是不起效的。

原因:在ThinkPHP\Library\Think\Template.class.php 文件,compiler方法少了以下的一段代码导致的:

if(C('TMPL_STRIP_SPACE')) {
/* 去除html空格与换行 */
    $find = array('~>\\s+<~','~>(\\s+\\n|\\r)~');
    $replace = array('><','>');
    $tmplContent = preg_replace($find, $replace, $tmplContent);
}




最终的代码是这样的. (如果不会改就直接复制下面的代码替换你的代码吧!)

protected function compiler($tmplContent) {
    //模板解析
    $tmplContent =  $this->parse($tmplContent);
    // 还原被替换的Literal标签
    $tmplContent =  preg_replace_callback('//is', array($this, 'restoreLiteral'), $tmplContent);
    // 添加安全代码
    $tmplContent =  ''.$tmplContent;
    if(C('TMPL_STRIP_SPACE')) {
        /* 去除html空格与换行 */
        $find           = array("~>\\s+<~","~>(\\s+\\n|\\r)~");
        $replace        = array('><','>');
        $tmplContent    = preg_replace($find, $replace, $tmplContent);
    }
    // 优化生成的php代码
    $tmplContent = str_replace('?>




php清除html,php去除空格与换行,php清除空白行和换行,提取页面纯文本

实用的php清除html,换行,空格类,php去除空格与换行,php清除空白行和换行,提取页面纯文本内容

方法一:

function DeleteHtml($str) 
{ 
$str = trim($str); //清除字符串两边的空格
$str = preg_replace("/\\t/","",$str); //使用正则表达式替换内容,如:空格,换行,并将替换为空。
$str = preg_replace("/\\r\\n/","",$str); 
$str = preg_replace("/\\r/","",$str); 
$str = preg_replace("/\\n/","",$str); 
$str = preg_replace("/ /","",$str);
$str = preg_replace("/  /","",$str);  //匹配html中的空格
return trim($str); //返回字符串
}



调用方法

DeleteHtml($str);   $str 为需要清除的页面字符串

方法二:

strip_tags() 函数剥去 HTML、XML 以及 PHP 的标签。
strip_tags() 函数官方介绍: http://www.php.net/manual/zh/function.strip-tags.php

class delhtml{
public function DeleteHtml($str) 
{ 
$str = trim($str); //清除字符串两边的空格
$str = strip_tags($str,""); //利用php自带的函数清除html格式
$str = preg_replace("/\\t/","",$str); //使用正则表达式替换内容,如:空格,换行,并将替换为空。
$str = preg_replace("/\\r\\n/","",$str); 
$str = preg_replace("/\\r/","",$str); 
$str = preg_replace("/\\n/","",$str); 
$str = preg_replace("/ /","",$str);
$str = preg_replace("/  /","",$str);  //匹配html中的空格
return trim($str); //返回字符串
}
}



调用方法

$delhtml=new delhtml();
$doreplace=$delhtml->DeleteHtml($doreplace);//需要处理的页面字符串



方法三:


去除字符串内部的空行:

$str = preg_replace("/(s*?r?ns*?)+/","n",$str);

去除全部的空行,包括内部和头尾:

$str = preg_replace('/($s*$)|(^s*^)/m', '',$str);

总结:三种方式方法过滤清除页面中的换行及空白行、空白换行,都有相同的效果,大家看实际使用情况吧。

本文来源:http://www.bbyears.com/jiaocheng/82508.html