首页 > 编程技术 > php

PHP移除指定HTML标签方法总结

发布时间:2016-11-25 17:27

在php中我们最常用的指定HTML标签可以直接使用strip_tags函数来替换了,利用它可以过滤所有的html标签哦,下面我来给大家介绍除了此函数之外的其它办法。

有时候我们需要把html标签页存到数据库里,但是有些场合却需要拿无html标签的纯数据,这个时候就要对带html标签的数据进行处理,把html标签都去掉。平时用 htmlspecialchars() 来过滤html,但是把html的字符转义了,最后显示出来的就是html源代码,利用strip_tags()就可以把html标签去除掉。


PHP默认的函数有移除指定html标签,名称为strip_tags,在某些场合非常有用。

strip_tags


strip_tags — Strip HTML and PHP tags from a string


string strip_tags ( string str [, string allowable_tags] )

弊端 :


这个函数只能保留想要的html标签,就是参数string allowable_tags。

这个函数的参数allowable_tags的其他的用法。

 代码如下 复制代码


strip_tags($source, ”); 去掉所以的html标签。
strip_tags($source, ‘<div><img><em>’); 保留字符串中的div、img、em标签。

如果想去掉的html的指定标签。那么这个函数就不能满足需求了。


于是乎我用到了这个函数。

 代码如下 复制代码

function strip_only_tags($str, $tags, $stripContent = FALSE) {
  $content = '';
 
  if (!is_array($tags)) {
    $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
    if (end($tags) == '') {
      array_pop($tags);
    }
  }
 
  foreach($tags as $tag) {
    if ($stripContent) {
      $content = '(.+<!--'.$tag.'(-->|s[^>]*>)|)';
    }
 
    $str = preg_replace('#<!--?'.$tag.'(-->|s[^>]*>)'.$content.'#is', '', $str);
  }
 
  return $str;
}


参数说明


$str  — 是指需要过滤的一段字符串,比如div、p、em、img等html标签。
$tags — 是指想要移除指定的html标签,比如a、img、p等。
$stripContent = FALSE  — 移除标签内的内容,比如将整个链接删除等,默认为False,即不删除标签内的内容。

使用说明

 代码如下 复制代码


$target = strip_only_tags($source, array(‘a’,'em’,'b’));移除$source字符串内的a、em、b标签。

$source='<div><a href="" target="_blank"><img" width=100% src="logo.png" border="0" alt="Welcome to linzl." />This a example from<em>lixiphp</em></a><strong>!</strong></div>
 ';
 
$target = strip_only_tags($source, array('a','em'));
 
//target results
//<div><img" width=100% src="/logo.png" border="0" alt="Welcome to lixiphp." />This a example from<strong>!</strong></div>

其它办法

 代码如下 复制代码


<?php
//取出br标记
function strip($str)
{
$str=str_replace("<br>","",$str);
//$str=htmlspecialchars($str);
return strip_tags($str);
}
?>


一个自定义的函数

/

 代码如下 复制代码
**
 * 取出html标签
 *
 * @access public
 * @param string str
 * @return string
 *
 */
function deletehtml($str) {
    $str = trim($str); //清除字符串两边的空格
    $str = strip_tags($str,"<p>"); //利用php自带的函数清除html格式。保留P标签
    $str = preg_replace("/t/","",$str); //使用正则表达式匹配需要替换的内容,如:空格,换行,并将替换为空。
    $str = preg_replace("/rn/","",$str);
    $str = preg_replace("/r/","",$str);
    $str = preg_replace("/n/","",$str);
    $str = preg_replace("/ /","",$str);
    $str = preg_replace("/  /","",$str);  //匹配html中的空格
    return trim($str); //返回字符串
}
 
php默认时区是欧美国家的所以与我们中国时区相差了整整8小时哦,下面我来给各位介绍php设置时区方法,有需要了解的朋友可进入参考。

在 php.ini 中,默认是 date.timezone = UTC。修改为中国时区,修改为 date.timezone = PRC。如果直接写 GMT 格式的,是 date.timezone = Etc/GMT+8。

另外,也可以在 PHP 页面头中设置。

 代码如下 复制代码

date_default_timezone_set('PRC');


在PHP5中, 有很多方法可以设置或者获取默认的时区设置,例如,使用date_default_timezone_setl函数来设置时区

 代码如下 复制代码

<?php
    date_default_timezone_set("Asia/Shanghain"); //设置时区为上海
?>

或者 设置东京的时区代码为:

<?php
    date_default_timezone_set("Asia/Tokyo");
?>

系统初始化时,加上

ini_set('date.timezone','Asia/Shanghai'); 

date_default_timezone_set("PRC"); 

就将解决时区相差8


还有如果你有php.ini管理权限可直接在php.ini中修改哦


手动修改php.ini设置

打开php找到date.timezone = "PRC" 如有去掉前面的分号,没有的话手动添加!

 

装上PHP5后你会发现这样的问题:

 

 代码如下 复制代码
<?php  
$atime=date("Y-m-d H:i:s");  
echo $atime;  
?> 
<?php
$atime=date("Y-m-d H:i:s");
echo $atime;
?>

你也许会发现,输出的时间和你现在的时间是不相同的。

原因是假如你不在程序或配置文件中设置你的服务器当地时区的话,PHP所取的时间是格林威治标准时间,所以和你当地的时间会有出入。

格林威治标准时间和北京时间大概差8个小时左右 那么我们如何避免时间误差呢?

我们一起来看看解决方法:

在页头使用date_default_timezone_set()设置我的默认时区为北京时间。

 代码如下 复制代码


<?  
date_default_timezone_set('PRC');  
echo date('Y-m-d H:i:s');  
?> 


时间和服务器当前时间一样了。

如果发生插入数据库错误的话,请确保 date('Y-m-d H:i:s') 中的 H 为大写。

本文章来给大家介绍一个利用PHP转换文件夹下所有文件的编码,这种我们很适用一次批量转换多个文件的编辑哦,注意只转一次哦


实例

 

 代码如下 复制代码
<?php
/**
 * 把一个文件夹里的文件全部转码 只能转一次 否则全部变乱码
 * @param string $filename
 */
function iconv_file($filename,$input_encoding='gbk',$output_encoding='utf-8')
{
if(file_exists($filename))
{
if(is_dir($filename))
{
foreach (glob("$filename/*") as $key=>$value)
{
iconv_file($value);
}
}
else 
{
$contents_before = file_get_contents($filename);
/*$encoding = mb_detect_encoding()($contents_before,array('CP936','ASCII','GBK','GB2312','UTF-8'));
echo $encoding;
if($encoding=='UTF-8')  mb_detect_encoding函数不工作
{
return;
}*/
$contents_after = iconv($input_encoding,$output_encoding,$contents_before);
file_put_contents($filename, $contents_after);
}
}
else 
{
echo '参数错误';
return false;
}
}
iconv_file('./test');
?>
在php中要替换串中指定字符我们一般会一次全部替换,如str_replace函数,但有时只想替换第一次出现的,像文章的关键词替换了,这个如果有100个不可能出现100次啊,我只想限制几次了,下面我来给各位介绍实现方法。

$str='这是字符串我只替换ABC一次后面的ABC我不替换了,有没有办法实现。';

把第一个abc替换成xyz,由于要替换的字符串是固定的,很多人想到了用str_replace()函数,看看这个函数的使用是不是我们要的

str_replace( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

不小心还真以为是我们想要的呢,最后那个参数是返回替换发生的总次数,它是一个引用变量,而不是我要想要的指定它将替换几次,所以用str_replace()是不行的

preg_replace()是可以实现的,可惜用了正则,

 代码如下 复制代码

$str=preg_replace('/abc/','abc',$str,1);
echo $str;

显示email为 从@前2位(含)开始向前隐藏4位

 代码如下 复制代码

function show_email_2($string){
        $first = strpos($string, '@');
        //var_dump($first);
        if($first==1){
            $string = '****'.$string;
        }
        if($first>1 && $first<=5){
            $string = substr_replace($string,'****',0,$first-1);           
        }
        if($first>5){
            $string = substr_replace($string,'****',$first-5,4);
        }
       
        var_dump($string);
        return $string;
    }
    //show_email_2('22@163.com');        //输出-->****2@163.com
    //show_email_2('22@22.com');        //输出-->****2@22.com
    show_email_2('6123456@163.com');    //输出-->61****6@163.com

有没有不用正则的,嗯可以这样

$replace='xyz';
if(($position=strpos($str,$replace))!==false){
     $leng=strlen($replace);
    $str=substr_replace($str,'abc',$position,$leng);
}
echo $str;

如果我想替换到指定次数可参考下面方法

 

 代码如下 复制代码

<?php
/*
 * $text是输入的文本;
 * $word是原来的字符串;
 * $cword是需要替换成为的字符串;
 * $pos是指$word在$text中第N次出现的位置,从1开始算起
 * */
function changeNstr($text,$word,$cword,$pos=1){
$text_array=explode($word,$text);
$num=count($text_array)-1;
if($pos>$num){
return "the number is too big!or can not find the $word";
}
$result_str='';
for($i=0;$i<=$num;$i++){
if($i==$pos-1){
$result_str.=$text_array[$i].$cword;
}else{
$result_str.=$text_array[$i].$word;}

}

return rtrim($result_str,$word);
}
$text='hello world hello pig hello cat hello dog hello small boy';
$word='hello';
$cword='good-bye';
echo changeNstr($text,$word,$cword,3);
//输出:hello world hello pig good-bye cat hello dog hello small boy
?>

实例都很好理解,如果你不想深入了解我们直接使用str_replace即可实例了。

今天没事做自己写了一个php curl 伪造IP来源程序实例程序,这里可以 伪造IP来源, 伪造域名, 伪造用户信息,有需要了解的朋友可参考。

定义伪造用户浏览器信息HTTP_USER_AGENT

 代码如下 复制代码

$binfo =array('Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; InfoPath.2; AskTbPTV/5.17.0.25589; Alexa Toolbar)','Mozilla/5.0 (Windows NT 5.1; rv:22.0) Gecko/20100101 Firefox/22.0','Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET4.0C; Alexa Toolbar)','Mozilla/4.0(compatible; MSIE 6.0; Windows NT 5.1; SV1)',$_SERVER['HTTP_USER_AGENT']);
//123.125.68.*
//125.90.88.*

定义伪造IP来源段,这里我找的是百度的IP地址

 代码如下 复制代码

$cip = '123.125.68.'.mt_rand(0,254);
$xip = '125.90.88.'.mt_rand(0,254);
$header = array(
'CLIENT-IP:'.$cip,
'X-FORWARDED-FOR:'.$xip,
);

利用curl开始向服务器发送伪造信息

 代码如下 复制代码

function getimgs( $url,$userinfo,$header)
{
 $ch = curl_init();
 $timeout = 5;
 curl_setopt ($ch, CURLOPT_URL, "$url");
 curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
 curl_setopt ($ch, CURLOPT_REFERER, "http://www.baidu.com/");
 curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt ($ch, CURLOPT_USERAGENT, "$userinfo");
 curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
 $contents = curl_exec($ch);
 curl_close($ch);
 return $contents;
}

获取到数据我们再保存

 代码如下 复制代码

function saveimgs( $handle )
{
 $fp = fopen('a.jpg',"w");
 fwrite($fp,$handle);
 unset($fp);
 unset($handle);
}

测试伪造IP实例

 代码如下 复制代码

$url ='http://www.111cn.net/img/logo.jpg';
$u = $binfo[mt_rand(0,3)];
saveimgs(getimgs($url,$u,$header));

这样就在你当前目录保存成功了一个文件a.jpg文件,我现可以查看服务器日志是不是我们自定的用户信息呢

192.168.1.108 - - [22/Jul/2013:10:29:37 +0800] "GET /test.php HTTP/1.1" 200 1244 "-" "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; InfoPath.2; AskTbPTV/5.17.0.25589; Alexa Toolbar)"
192.168.1.108 - - [22/Jul/2013:10:29:37 +0800] "GET / HTTP/1.1" 200 40538 "http://www.baidu.com/" "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET4.0C; Alexa Toolbar)"
192.168.1.108 - - [22/Jul/2013:10:29:37 +0800] "GET /test.php HTTP/1.1" 200 1244 "-" "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; InfoPath.2; AskTbPTV/5.17.0.25589; Alexa Toolbar)"
192.168.1.108 - - [22/Jul/2013:10:29:37 +0800] "GET / HTTP/1.1" 200 40538 "http://www.baidu.com/" "Mozilla/5.0 (Windows NT 5.1; rv:22.0) Gecko/20100101 Firefox/22.0"

看出来了吧,完全正确啊,只是IP地址我怎么没测试出来,这个使用php获取ip地址时会是显示我伪造IP地址了

标签:[!--infotagslink--]

您可能感兴趣的文章: