首页 > 编程技术 > php

php利用正则过滤链接、标签,空格,换行符程序

发布时间:2016-11-25 15:49

本文章详细的总结了php利用正则过滤链接、标签,空格,换行符程序,有需要学习的朋友可参考一下。


strip_tags函数

strip_tags --- 去除字串中的HTML和PHP标签

语法 : string strip_tags (string str [, string allowable_tags])

 代码如下 复制代码

<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "n";

// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
?>

正则过滤各种标签,空格,换行符

 代码如下 复制代码

$str=preg_replace("/s+/", " ", $str); //过滤多余回车
$str=preg_replace("/<[ ]+/si","<",$str); //过滤<__("<"号后面带空格)
$str=preg_replace("/<!–.*?–>/si","",$str); //注释
$str=preg_replace("/<(!.*?)>/si","",$str); //过滤DOCTYPE
$str=preg_replace("/<(/?html.*?)>/si","",$str); //过滤html标签
$str=preg_replace("/<(/?head.*?)>/si","",$str); //过滤head标签
$str=preg_replace("/<(/?meta.*?)>/si","",$str); //过滤meta标签
$str=preg_replace("/<(/?body.*?)>/si","",$str); //过滤body标签
$str=preg_replace("/<(/?link.*?)>/si","",$str); //过滤link标签
$str=preg_replace("/<(/?form.*?)>/si","",$str); //过滤form标签
$str=preg_replace("/cookie/si","COOKIE",$str); //过滤COOKIE标签
$str=preg_replace("/<(applet.*?)>(.*?)<(/applet.*?)>/si","",$str); //过滤applet标签
$str=preg_replace("/<(/?applet.*?)>/si","",$str); //过滤applet标签
$str=preg_replace("/<(style.*?)>(.*?)<(/style.*?)>/si","",$str); //过滤style标签
$str=preg_replace("/<(/?style.*?)>/si","",$str); //过滤style标签
$str=preg_replace("/<(title.*?)>(.*?)<(/title.*?)>/si","",$str); //过滤title标签
$str=preg_replace("/<(/?title.*?)>/si","",$str); //过滤title标签
$str=preg_replace("/<(object.*?)>(.*?)<(/object.*?)>/si","",$str); //过滤object标签
$str=preg_replace("/<(/?objec.*?)>/si","",$str); //过滤object标签
$str=preg_replace("/<(noframes.*?)>(.*?)<(/noframes.*?)>/si","",$str); //过滤noframes标签
$str=preg_replace("/<(/?noframes.*?)>/si","",$str); //过滤noframes标签
$str=preg_replace("/<(i?frame.*?)>(.*?)<(/i?frame.*?)>/si","",$str); //过滤frame标签
$str=preg_replace("/<(/?i?frame.*?)>/si","",$str); //过滤frame标签
$str=preg_replace("/<(script.*?)>(.*?)<(/script.*?)>/si","",$str); //过滤script标签
$str=preg_replace("/<(/?script.*?)>/si","",$str); //过滤script标签
$str=preg_replace("/javascript/si","Javascript",$str); //过滤script标签
$str=preg_replace("/vbscript/si","Vbscript",$str); //过滤script标签
$str=preg_replace("/on([a-z]+)s*=/si","On\1=",$str); //过滤script标签
$str=preg_replace("/&#/si","&#",$str); //过滤script标签

php 正则过滤html 的超链接

 代码如下 复制代码
<?php
echo preg_replace("/(?<=href=)([^>]*)(?=>)/i","#", "<a href='www.111cn.net'>你好,点这里看看</a><a href='www.111cn.net'>你好,点这里看看</a>");
?>

正则:/(?<=href=)([^>]*)(?=>)/
(?<=exp) 匹配exp后面的位置
(?=exp) 匹配exp前面的位置
此正则 匹配 在 href= 之后 “>” 之前 的 非 “>” 的所有字符
例子:<a href='www.111cn.net'>
找到这些字符(url)用 # 替换,就可以去掉html里的所有链接。

检查文件或目录是否存在 ,我们使用了php中常用的函数file_exists,这个函数就可以实现我想要的功能,下面大家慢慢参考一下。

下面是一个简单的检查文件是否存在的实例代码:

 代码如下 复制代码

<?php
$filename = '/path/to/foo.txt';

if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}
?>

如果文件存在,执行该 PHP 文件的显示结果是:

The file C:blablaphphello.txt exists.

如果文件不存在,执行该 PHP 文件的显示结果是:

The file C:blablaphphello.txt does not exist.

你也可以用file_exists 函数测试某个目录是否存在,示例代码如下:

 代码如下 复制代码

if (file_exists("C:\blabla\php"))
  {echo "yes";}
else
  {echo "no";}


实例

 代码如下 复制代码

/**
 * 文件或目录权限检查函数
 *
 * @access          public
 * @param           string  $file_path   文件路径
 * @param           bool    $rename_prv  是否在检查修改权限时检查执行rename()函数的权限
 *
 * @return          int     返回值的取值范围为{0 <= x <= 15},每个值表示的含义可由四位二进制数组合推出。
 *                          返回值在二进制计数法中,四位由高到低分别代表
 *                          可执行rename()函数权限、可对文件追加内容权限、可写入文件权限、可读取文件权限。
 */
function file_mode_info($file_path)
{
    /* 如果不存在,则不可读、不可写、不可改 */
    if (!file_exists($file_path))
    {
        return false;
    }
    $mark = 0;
    if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')
    {
        /* 测试文件 */
        $test_file = $file_path . '/cf_test.txt';
        /* 如果是目录 */
        if (is_dir($file_path))
        {
            /* 检查目录是否可读 */
            $dir = @opendir($file_path);
            if ($dir === false)
            {
                return $mark; //如果目录打开失败,直接返回目录不可修改、不可写、不可读
            }
            if (@readdir($dir) !== false)
            {
                $mark ^= 1; //目录可读 001,目录不可读 000
            }
            @closedir($dir);
            /* 检查目录是否可写 */
            $fp = @fopen($test_file, 'wb');
            if ($fp === false)
            {
                return $mark; //如果目录中的文件创建失败,返回不可写。
            }
            if (@fwrite($fp, 'directory access testing.') !== false)
            {
                $mark ^= 2; //目录可写可读011,目录可写不可读 010
            }
            @fclose($fp);
            @unlink($test_file);
            /* 检查目录是否可修改 */
            $fp = @fopen($test_file, 'ab+');
            if ($fp === false)
            {
                return $mark;
            }
            if (@fwrite($fp, "modify test.rn") !== false)
            {
                $mark ^= 4;
            }
            @fclose($fp);
            /* 检查目录下是否有执行rename()函数的权限 */
            if (@rename($test_file, $test_file) !== false)
            {
                $mark ^= 8;
            }
            @unlink($test_file);
        }
        /* 如果是文件 */
        elseif (is_file($file_path))
        {
            /* 以读方式打开 */
            $fp = @fopen($file_path, 'rb');
            if ($fp)
            {
                $mark ^= 1; //可读 001
            }
            @fclose($fp);
            /* 试着修改文件 */
            $fp = @fopen($file_path, 'ab+');
            if ($fp && @fwrite($fp, '') !== false)
            {
                $mark ^= 6; //可修改可写可读 111,不可修改可写可读011...
            }
            @fclose($fp);
            /* 检查目录下是否有执行rename()函数的权限 */
            if (@rename($test_file, $test_file) !== false)
            {
                $mark ^= 8;
            }
        }
    }
    else
    {
        if (@is_readable($file_path))
        {
            $mark ^= 1;
        }
        if (@is_writable($file_path))
        {
            $mark ^= 14;
        }
    }
    return $mark;
}


 

PHP判断目录是否存在    

 代码如下 复制代码

/****************************************************
     * 将xml数据流,写入到xml文件
     * @param $xmlData
     * @return bool|string
     */
    function writeXmlFile($xmlData)
    {
        $time = time(); //获取时间戳,用于给文件命名
        $path = dirname(__FILE__); //获取当前绝对路径
        $path = substr_replace($path, "", stripos($path, "actions\data")); //将此文件所在的固有路径替换成空
        $path .= "xmlFiles\"; //存放目录名

        /*判断目标目录是否存在,不存在则新建*/
        if(!is_dir($path))
        {
            mkdir($path); //新建目录
        }

        /*记录完整路径和文件名*/
        $filePathAndName = $path.$time.".xml";

        /*打开文件,文件名为<时间戳> + <.xml>*/
        $fp = fopen($filePathAndName, "w");
        if(!$fp)
        {
            return false;
        }

        /*写入文件流*/
        $flag = fwrite($fp, $xmlData);
        if(!$flag)
        {
            return false;
        }

        fclose($fp);

        return $filePathAndName;
    }

php 网页生成word文档的实例程序 在需要的朋友可参考一下。

在这篇文章中主要解决两个问题:

1:在php中如何把html中的内容生成到word文档中

2:php把html中的内容生成到word文档中时,不居中显示问题,即会默认按照web视图进行显示。

3:php把html中的内容生成到word文档中时,相关样式不兼容问题

正文:

  

 代码如下 复制代码

echo '<html xmlns:o="urn:schemas-microsoft-com:office:office"  xmlns:w="urn:schemas-microsoft-com:office:word"  xmlns="http://www.w3.org/TR/REC-html40">
              <head>
                   <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
                   <xml><w:WordDocument><w:View>Print</w:View></xml>
                   <script" width=100% src="includes/js/ztree/js/jquery-1.4.4.min.js" type="text/javascript"></script>
            </head>';

echo '<body><table class="table_dayin">
    <caption class="table_caption">';
    echo "数字化教学系统电子备课稿<br>
        <span>学科 <em style="border-bottom: 1px solid #545454;">语文</em>学校 <em style="border-bottom: 1px solid #545454;">实验中学</em></span>
    </caption>";
echo '</table></body></html>';

                ob_start(); //打开缓冲区
 header("Cache-Control: public");
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");

if (strpos($_SERVER["HTTP_USER_AGENT"],'MSIE')) {
  header('Content-Disposition: attachment; filename=test.doc');
  }else if (strpos($_SERVER["HTTP_USER_AGENT"],'Firefox')) {
  Header('Content-Disposition: attachment; filename=test.doc');
  } else {
  header('Content-Disposition: attachment; filename=test.doc');
  }
  header("Pragma:no-cache");
header("Expires:0");
ob_end_flush();//输出全部内容到浏览器

注:以上代码部分提供了在php程序文件中生成内容到word文档中并提供下载功能。

例子

 代码如下 复制代码

<?php
//初始化session
session_start();
// 包含数据库连接文件和头文件
?>
<html>
<head>
<title>试卷生成</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<?
include('head.php');
require ('dbconnect.php');
?>
<?PHP
$juge=0;
for($i=1;($i<100);$i++)
{
$a=$i;
if(isset($_POST[$a]))
{
if($juge==0)
$sql.=" id=".$_POST[$a];
else
$sql.=" or id=".$_POST[$a];
$juge=1;
}
}
if($sql!="")
{
$sql="SELECT * FROM test WHERE".$sql;
$result_array=array(); //返回数组
$i=0; //数组下标
$query_result=@mysql_query($sql,$conn);
while($row=@mysql_fetch_object($query_result))
{
$i++;
$cout.=$i."&nbsp;&nbsp;";
$cout.="题目难度:".$row->difficulty."<br>";
$cout.="&nbsp;&nbsp;&nbsp;".$row->content."<br><br>";
}//while

?>
<?php
class word
{
function start()
{
ob_start();
print'<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns="http://www.w3.org/TR/REC-html40">';
}

function save($path)
{

print "</html>";
$data = ob_get_contents();

ob_end_clean();
$this->wirtefile ($path,$data);
}
function wirtefile ($fn,$data)
{
$fp=fopen($fn,"wb");
fwrite($fp,$data);
fclose($fp);
}
}
/*-------word class End-------*/
$word=new word;
$word->start();
echo $cout;
$wordname="word/".time().".doc";
$word->save($wordname);//保存word并且结束.
?>
<div align="center"><a href="<?php echo $wordname ; ?>" target=_blank class="unnamed1">试卷已经生成,请点击这里查看</a>
<?PHP
}
else
{
?>
</div>
<div align="center"><span class="unnamed1">您输入的条件不足,请重新输入!</span>
<?PHP
}
?>
</div>
</html>

一个简单的php邮箱难函数,有需要的学习的朋友可参考本文章。

一个简单PHP验证邮箱合法性的函数,功能很全,记下备用。

 代码如下 复制代码
$mail = 'wan.ch_un0222@126.qq.com';
 
function vaildEmail($mail){
 
 //验证邮箱
 
 if (empty($mail) || !preg_match("/^[-a-zA-Z0-9_.]+@([0-9A-Za-z][0-9A-Za-z-]+.)+[A-Za-z]{2,5}$/",$mail)){
 
     return false;     
 
 }else{
 
     return true;
 
 }
 
}
GBK简体字符集的编码是同时用1个字节和2个字节来表示的。当高位是0x00~0x7f时,为一个字节,高位为0x80以上时用2个字节表示

为了识别双字节的字符,比如汉字或日文韩文等都是占两字节的,每字节高位为1,而一般西文字符只有一个字节,七位有效编码,高位为0
而0x80对应的二进制代码为1000 0000,最高位为一,代表汉字.汉字编码格式通称为10格式. 一个汉字占2字节,但只代表一个字符

GBK简体字符集的编码是同时用1个字节和2个字节来表示的。当高位是0x00~0x7f时,为一个字节,高位为0x80以上时用2个字节表示"

注:括号里面都是2进制
当你发现一个字节的内容大于0x7f,那它肯定是个(跟另外一个字节拼凑成一个)汉字,如何判断肯定大于0x7f呢?
0x7f(1111111)后面一个数就是0x80(10000000),所以想要大于0x7f,这个字节的最高位都肯定是1,我们只需要判断这个最高位是否为1就行了。

判断方法:
位与(相同的位都是1的才为1,否则为0):
如:要判断一个数的第三位是否是1,只要跟4(100)位与,判断一个数的第2位是否为1就跟2(10)位与.
同理判断第八位是否为1只要跟(10000000)也就是0x80位与了.

这里为什么不用>0x7f,php可能还行,但在其他强类型语言里面,1个字节的最高位用来标示负数,一个负数肯定不可能大于0x7f(最大的整数)

再举个例子:

 代码如下 复制代码

a的assic码是97(1100001)
A的assic码是65(1000001)

b的assic码是98(1100010)
b的assic码是66(1000010)

发现一个规律:一个a-z的字母,只要是小写字母,第六位肯定是1,我们可以用这个来判断大小写:
这时候只要跟用以个字母跟0x20(100000)来位与判断:

 代码如下 复制代码
if(ord($a)&0x20){
        //大写
}

如何把所有字母改成大写?第六位的1改成0就行了:

 代码如下 复制代码
$a='a';
$a        = chr(ord($a)&(~0x20));
echo $a;
标签:[!--infotagslink--]

您可能感兴趣的文章: