php中清除文章中所有空格程序

 更新时间:2016年11月25日 15:40  点击:2081
清除字符串中空白或空格我们可以使用ereg_replace函数进行替换了,下面给大家整理了一个页面希望对各位有帮助。

去除所有空白

 代码如下 复制代码
function delete($str) {
    $str = trim($str);
    $str = ereg_replace("\t","",$str);
    $str = ereg_replace("\r\n","",$str);
    $str = ereg_replace("\r","",$str);
    $str = ereg_replace("\n","",$str);
    $str = ereg_replace("    ","",$str);
    return trim($str);
}

去除所有注释用preg_replace()函数把注释替换成空(是空,不是空格)。
 去掉字符串中的空格 str_replace(' ','',$cat_name)

 代码如下 复制代码
 
$str = ” This line contains\tliberal \r\n use of   whitespace.\n\n”;
$str = trim($str);// 首先去掉头尾空格
$str = preg_replace(’/\s(?=\s)/’, ‘’, $str);// 接着去掉两个空格以上的
$str = preg_replace(’/[\n\r\t]/’, ‘ ‘, $str);// 最后将非空格替换为一个空格

使用上面的例子可以去掉所有多余的空格。
首先使用TRim()去头尾空格,
接着用preg_replace()去掉重复的空格。
当中的(?=)表示只匹配后面的空格跟随前面的空格的空格。
 

 代码如下 复制代码

<?php
$str1="   tt 七夕快乐!nr"; //这里定义一个字符变量,其中包括"空格","t", 水平制表符,"n",换行符
//这里主要调用trim()函数去除空格等,trim()函数用于去除字符中的""空格,"t"水平制表符"n"换行符,"r"回车符
//"\0"字符串结束符,"xOB"垂直制表符。如果想通过此函数过滤掉特殊的字符,可以制定第二个参数。
echo trim($str1)."<br>";
//这里是去除$str1变量中带有tt的字符
echo trim($str1," tt")."<br>";
//定义变量$str2其中包括"."和空格
$str2="... 情人节快乐!...   中国...";
//调用trim()函数去除$str2变量中的空格
echo trim($str2)."<br>";
//ltrim()函数用于去除字符串左边的空格或指定字符串,其默认的字符同trim一样。因为这里指定了第二个参数,
//所以只去除$str2变量中左边的"."
echo ltrim($str2,".")."<br>";
//ltrim()函数用于去除字符串(右)边的空格或指定字符串,其默认的字符同trim一样。因为这里指定了第二个参数,
//所以只去除$str2变量中左边的"."
echo rtrim($str2,".")."<br>";
?>

<?php
echo substr("today is father day!",0)."<br>";
echo substr("today is father day!",6,2)."<br>";//这里只截取字符串中第6字符开始截取,并只截取2个字符
echo substr("today is father day!",-5,5)."<br>";//这里从字符串的倒数第5个字符开始截取,截取5个字符
echo substr("today is father day!",0,-5)."<br>";//这里只截取字符串中的首个字符开始截取,截取到字符串的倒数第5个
echo substr("today is father day!",-5,-1)."<br>";//这里从字符串的倒数第5个字符开始截取,截取倒数第一个字符
?>

补充一个:php注释和去除空格

 代码如下 复制代码


/**
 * 去除代码中的空白和注释
 * @param string $content 代码内容
 * @return string
 */
function strip_whitespace($content) {
    $stripStr   = '';
    //分析php源码
    $tokens     = token_get_all($content);
    $last_space = false;
    for ($i = 0, $j = count($tokens); $i < $j; $i++) {
        if (is_string($tokens[$i])) {
            $last_space = false;
            $stripStr  .= $tokens[$i];
        } else {
            switch ($tokens[$i][0]) {
                //过滤各种PHP注释
                case T_COMMENT:
                case T_DOC_COMMENT:
                    break;
                //过滤空格
                case T_WHITESPACE:
                    if (!$last_space) {
                        $stripStr  .= ' ';
                        $last_space = true;
                    }
                    break;
                case T_START_HEREDOC:
                    $stripStr .= "<<<THINK\n";
                    break;
                case T_END_HEREDOC:
                    $stripStr .= "THINK;\n";
                    for($k = $i+1; $k < $j; $k++) {
                        if(is_string($tokens[$k]) && $tokens[$k] == ';') {
                            $i = $k;
                            break;
                        } else if($tokens[$k][0] == T_CLOSE_TAG) {
                            break;
                        }
                    }
                    break;
                default:
                    $last_space = false;
                    $stripStr  .= $tokens[$i][1];
            }
        }
    }
    return $stripStr;
}

$_FILES与move_uploaded_file就可以在php代码中实现文件或图片上传了,这个比起很多编程语言来讲php上传功能是最简单最好用的了,下面来看个上传图片工作代码。
 代码如下 复制代码


<?php
 session_start();
 ?>
 <html xmlns="http://www.111cn.net/ 1999/xhtml">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>PHP上传文件</title>
 <style>
 * {margin:0; padding:0; list-style:none;}
 .content {width:400px; height:200px; margin:0 auto; margin-top:60px;

background:#ffd3b6; border:dashed 1px #f90}
 .content h1 { width:400px; height: 30px; line-height:30px; text-align:

center; font-family:"微软雅黑"; font-size:14px; color:#000}
 .content .error {width:300px; height:30px; line-height:30px;

text-align:center; margin:0 auto; color:#f00}
 .content .con {width:340px; height:auto; margin:0 auto; font-size:12px;}
 .content #file { width:280px; height:20px; border:solid 1px #ccc;

background:#fff; margin:10px 0px 6px 0; font-size:12px;}
 .content #send { width:60px; height:22px; border:solid 1px #ccc;

background:#fff; font-size:12px; margin-top:10px;}
 </style>
 </head>

<body>
 <div>
 <h1>文件上传</h1>
 <div>
 <div>
 <?php
 if ($_GET['up']==up) {
 if ($_SESSION['file']==$_GET['irand']) {
 $_size=20000;                    //设置限制文件大小
 $_dir='phone/';                   //文件保存目录
 function size($_size) {
 //判断文件大小是否大于1024bit 如果大于,则将大小取值为KB
 if ($_size>1024*1024) {
 return round($_size/1024/1024,2).' MB';
 }else if ($_size>1024) {
 $_size=$_size/1024;
 return ceil($_size).'KB';
 }else {
 return $_size.' bit';
 }
 }
 //设置上传图片的类型,设置图片上传大小
 $_upfiles = array('image/jpeg','image/pjpeg','image/png','image/x-png','image/gif');
 if (is_array($_upfiles)) {
 if (!in_array($_FILES['userfile']['type'],$_upfiles)) {
 exit('请上传格式为:jpg,png,gif的文件<br /><a href="upload.php">返回</a>');
 }
 }
 if ($_FILES['userfile']['size']>$_size) {
 exit('上传文件不能超过:'.size($_size));
 }
 if ($_FILES['userfile']['error']>0) {
 switch ($_FILES['userfile']['error']) {
 case 1: echo '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值';
 break;
 case 2: echo '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值';
 break;
 case 3: echo '文件只有部分被上传';
 break;
 case 4: echo '没有文件被上传';
 break;
 case 6: echo '找不到临时文件夹';
 break;
 case 7: echo '文件写入失败';
 break;
 }
 exit;
 }
 //获取文件扩展名
 if (!is_dir($_dir)) {
 mkdir($_dir,0700);
 }
 $_rand=mt_rand(0,100000);
 $_n=explode('.',$_FILES['userfile']['name']);  //将文件名分割
 $_file_len=count($_n);         //返回数组长度
 $_name=$_dir.time().'_'.$_rand.'.'.$_n[$_file_len-1];

if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
 if (!@move_uploaded_file($_FILES['userfile']['tmp_name'],$_name)) {
 exit('文件移动失败');
 }else {
 echo '文件上传成功<br />';
 echo '文件路径:'.$_name.'<br />';
 echo '文件大小:'.size(filesize($_name));
 echo '<br /><a href="upload.php">返回继续上传</a>';
 }
 }else {
 exit('上传的临时文件不存在,无法将文件移动到指定文件夹');
 }
 //销毁session变量,有几种方法
 //第一种,销毁所有session变量:session_destroy();
 //第二种:销毁单个如:$_SESSION['file']=''
 session_destroy();
 exit;
 }else {
 exit('您已经提交过了,不能重复提交<br /><a href="upload.php">返回</a>');
 }
 }
 ?>
 </div>
 <?php $_irand=mt_rand(0,1000000); $_SESSION['file']=$_irand; ?>
 <form action="?up=up&irand=<?php echo $_irand; ?>" method="post" enctype="multipart/form-data">
 <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
 <input type="file" name="userfile" id="file"/><br />
 <input type="submit" name="send" value=" 点击上传 " id="send"/>
 </form>
 </div>
 </div>
 </body>
 </html>

大多数据站长做留言板功能都会与数据库连接起来了,今天我们给大家分享一个基于xml留言板程序了。

php中操作xml文档我们会使用SimpleXMLElement函数,我们先了解一下SimpleXMLElement函数用法
SimpleXML 函数允许您把 XML 转换为对象。
通过普通的属性选择器或数组迭代器,可以处理这个对象,就像处理任何其他对象一样。

例子

xml文档格式

 代码如下 复制代码

<?php
error_reporting(E_ALL ^ E_NOTICE);
$op=$_GET['op'];
$op || $op='list';

$filename='guestbook.xml';
if(is_file($filename)){
 $gb=simplexml_load_file($filename);
}else{
 $gb=new SimpleXMLElement("<?xml version='1.0' encoding='utf-8'?><guestbook></guestbook>");
}
if($op=='list'){
 header("Content-Type:text/html;charset=utf-8");
 if(is_object($gb)){
echo "<table>";
echo "<tr><th>ID</th><th>用户</th><th>标题</th><th>标题</th><th>内容</th><th>时间</th><th>IP</th></tr>";
foreach($gb->item as $v){
 echo "<tr>";
 echo "<td>".htmlspecialchars($v->id)."</td><td>".htmlspecialchars($v->user)."</td><td>".htmlspecialchars($v->title)."</td><td>".htmlspecialchars($v->content)."</td><td>".date("Y-m-d H:i",intval($v->time))."</td><td>".htmlspecialchars($v->ip)."</td>";
}
echo '<table>';
 }
 echo "<div><a href='guestbook.php?op=add'>添加</a></div>";
}elseif($op=='save'){
 if(@$_POST['user']){
$user=$_POST['user'];
$title=$_POST['title'];
$content=$_POST['content'];

/*
$id=@count($gb->item);
$nextid=$id+1;
*/
$nextid=1;
foreach($gb->item as $v){
 $idarr[]=(int)$v->id;
}
$nextid=max($idarr)+1;
$item=$gb->addChild('item');
$item->addChild("id",$nextid);
$item->addChild('user',$user);
$item->addChild('title',$title);
$item->addChild('content',$content);
$item->addChild('time',time());
$item->addChild('ip',$_SERVER['REMOTE_ADDR']);
$gb->asXML($filename);
//跳转页,中间页
header("Location: guestbook.php?op=list");
die;
 }
}elseif($op=='add'){
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
 <title>Document</title>
</head>
<body>
<form action="guestbook.php?op=save" method="post">
<div>用户:<input type="text" name="user"></div>
<div>标题:<input type="text" name="title"></div>
<div>留言:<textarea name="content" id="" cols="30" rows="10"></textarea></div>
<div><input type="submit"  value="提交留言"></div>
</form>
</body>
</html>
<?php
}
?>

前面有讲过一个目录遍历的例子,这个例子有一点不一样他可以利用php目录遍历出来的目录或文件进行一个树型的展示效果。

遍历出来的效果如下

php+jquery实现无限级目录遍历展示代码

程序代码


index.php 里面的jquery文件大家可百度下载一个,因为这是用来实现一个效果的

 代码如下 复制代码

<script src="jquery/jquery-1.3.1.js" type="text/javascript"></script>
<style type="text/css">
body
{font: normal 12px arial, tahoma, helvetica, sans-serif;margin:0;background:#fff;padding:30px;}
*{ margin:0; padding:0;}
ul{ visibility:visible; cursor:pointer;}
.simpleTree li{font-size:14px; list-style: none;margin:0 0 0 50px;padding:0 0 0 34px;line-height: 18px;margin-left:-13px;background: url(jquery/images/expandable.gif) 0 -2px no-repeat #fff;}
.simpleTree li span{display:inline;clear: left;white-space: nowrap;}
li.root{padding:0 0 0 20px;line-height:20px;background: url(jquery/images/root.gif) 0 2px no-repeat #fff;}
li.file{padding:0 0 0 35px;line-height:20px;background: url(jquery/images/leaf-last.gif) 0 2px no-repeat #fff;}
</style>
<script type="text/javascript">
$(function(){

 $(".simpleTree").children("li").find("ul").hide();
$("span").click(function(){
 var $this_ul=$(this).siblings("ul");
 if($this_ul.is(":visible")){
$this_ul.stop(false,true).hide();

 }else{
$(this).siblings("ul").stop(false,true).show().end().stop(false,true).siblings("ul").find("ul").hide();
 }

})


})

</script>
<?php

include("function.php");

$path="目录/";//目录名
echo "<ul class='simpleTree'><li class='root'><span>目录</span>"; //目录名,和path 中名称一样
list_dir($path);

echo "</ul></li>";
?>

function.php 这个文件包含了遍历目录的函数了

 代码如下 复制代码

<?php
/*输出当前目录下的所有文件数量*/
function files_count($path,  & $i=0){
if($opendir=opendir($path)){
//===============
while($file=readdir($opendir) ){
if($file!="."&&$file!=".."){
 if(is_file($path."/".$file)){
  $i++;
 ;
 }else{

  files_count($path."/".$file, $i);
 }

 }

}

//=============
return  "(".$i.")";
}

}

//echo files_count("目录/目录1/3/");

//=============================//
/*遍历目录*/
function list_dir($path){
if($opendir=opendir($path)){


}
echo "<ul>";
while($file=readdir($opendir)){
 if($file!="."&&$file!=".."){

  if(is_dir($path."/".$file)){

 

$bar=scandir($path."/".$file);
unset($bar[0]);
unset($bar[1]);
if(count($bar!==0)){
 echo "<li><span>".$file.files_count($path."/".$file)."</span>";
 list_dir($path."/".$file);
}


  }else{

   echo "<li class='file'><a  href='".$path."/".$file."'>".$file."</a></li>";
  }

  }

 }
echo "</ul></li>";
}
?>

我们用到最多的日志肯定是数字型的日期了,但有时工作需要要把日期转换成中文要怎么处理?下面一起来看一个php日期转中文程序代码吧。

如果我们直接使用date函数获取日期显示的是数字的,如下

 代码如下 复制代码

<?php  
   echo   date("Y-m-d");  
?>

输出的

2014-10-11

那么我们如果想得到

二零一四年十月十一日

怎么处理呢,后来看到一个朋友写了一句话函数

 代码如下 复制代码

<?php
#php日期转中文
$str = '2014-10-11';
echo str_replace(str_split('0123456789'), str_split('零一二三四五六七八九',3), date('Y',strtotime($str)).'年'.trim(str_replace('1十','十',implode('十', str_split(date('n',strtotime($str))))),'0').'月'.trim(str_replace('1十','十',implode('十', str_split(date('d',strtotime($str))))),'0')).'日';
?>

输出结果:

二零一四年十月十一日

[!--infotagslink--]

相关文章

  • @CacheEvict 清除多个key的实现方式

    这篇文章主要介绍了@CacheEvict 清除多个key的实现方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-02-13
  • php 取除连续空格与换行代码

    php 取除连续空格与换行代码,这些我们都用到str_replace与正则函数 第一种: $content=str_replace("n","",$content); echo $content; 第二种: $content=preg_replac...2016-11-25
  • IDEA中的clean,清除项目缓存图文教程

    这篇文章主要介绍了IDEA中的clean,清除项目缓存图文教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-09-25
  • php过滤所有的空白字符(空格、全角空格、换行等)

    在php中自带的trim函数只能替换左右两端的空格,感觉在有些情况下不怎么好使,如果要将一个字符串中所有空白字符过滤掉(空格、全角空格、换行等),那么我们可以自己写一个过滤函数。php学习str_replace函数都知道,可以批量替...2015-10-30
  • c#字符串去掉空格的二种方法(去掉两端空格)

    本文主要介绍了字符串去掉两端空格,并且将字符串中多个空格替换成一个空格的方法,需要的朋友可以参考下...2020-06-25
  • Vue如何优雅的清除定时器

    定时器如果不及时合理地清除,会造成业务逻辑混乱甚至应用卡死的情况,这个时就需要清除定时器,本文就介绍了Vue如何优雅的清除定时器,感兴趣的可以了解一下...2021-07-22
  • php过滤所有的空白字符(空格、全角空格、换行等)

    在php中自带的trim函数只能替换左右两端的空格,感觉在有些情况下不怎么好使,如果要将一个字符串中所有空白字符过滤掉(空格、全角空格、换行等),那么我们可以自己写一个过滤函数。php学习str_replace函数都知道,可以批量替...2015-10-30
  • pycharm 复制代码出现空格的解决方式

    这篇文章主要介绍了pycharm 复制代码出现空格的解决方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-16
  • Python 如何将字符串每两个用空格隔开

    这篇文章主要介绍了Python Python 如何将字符串每两个用空格隔开的实现方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-04-16
  • 帝国CMS最高效的几种随机文章的写法

    /*解决代码高亮太长不换行*/ .syntaxhighlighter{word-break:break-all;} uParse('#newstext', {rootPath: '/e/extend/ueditor/'}) php随机文章 方法1、WC写的高效随...2017-07-06
  • JavaScript过滤字符串中的中文与空格方法汇总

    这篇文章主要介绍了JavaScript过滤字符串中的中文与空格方法汇总 的相关资料,需要的朋友可以参考下...2016-03-09
  • JS清除文本框内容离开在恢复及鼠标离开文本框时触发js的方法

    多网站的需要填写的文本框在默认状态下都会给出一个默认的提示语言,当鼠标点击此文本框的时候能够将里面的默认文本清除,当删除输入的文本且焦点离开文本框的时候再将默认的文本写入文本框...2016-01-14
  • C#实现去除Strings中空格的方法

    这篇文章主要介绍了C#实现去除Strings中空格的方法,较为详细的介绍了C#实现去除字符串首尾及中间空格的方法,是非常实用的技巧,需要的朋友可以参考下...2020-06-25
  • 怎么清除sql server日志

    方法1: 第一步: backup log database_name with no_log 或者 backup log database_name with truncate_only --no_log和truncate_only是在这里是同义的,随便执行哪一句...2016-11-25
  • Bootstrap框架动态生成Web页面文章内目录的方法

    这篇文章主要介绍了Bootstrap框架动态生成Web页面文章内目录的方法,利用Bootstrap中的Affix和ScrollSpy插件便可以实现,需要的朋友可以参考下...2016-05-14
  • CSS不得不掌握的技巧【清除float浮动】

    本文我们来讲讲CSS必备掌握的重点:清除float浮动clear,掌握此内容,可以让你在css+div布局中,一些浮动问题得心应手。 一、浮动产生原因 一般浮动是什么情况呢?一般是...2016-09-14
  • 一篇入门的 Class 文章

    刚在大略浏览了一下首页更新的那篇有关Class的文章(指PHPE的那篇 http://www.phpe.net/articles/389.shtml ),很不错,建议看看。 对类的摸索~~俺用了半年时间才大概理解类的...2016-11-25
  • 清除aspx页面缓存的程序实现方法

    这篇文章主要介绍了清除aspx页面缓存的程序实现方法,非常实用,需要的朋友可以参考下...2020-06-25
  • php去除字符串首尾中英文空格程序

    下面本文章来给各位同学总结了几种php去除字符串首尾中英文空格程序实例,这里有用正则替换与trim系列函数删除,下面我们来看看。 例1.trim函数删除空格 trim()函...2016-11-25
  • 长文章分页代码

    <? $pieces = explode("<HR>", $news['content']);//以<HR>水平线分隔 $page=count($pieces); if(empty($move)){$move=0;}else{$move=$move;} echo $pieces[$move...2016-11-25