首页 > phper

php字符串处理函数




AddSlashes:    字符串加入斜线。
bin2hex:    二进位转成十六进位。
Chop:    去除连续空白。
Chr:    返回序数值的字符。
chunk_split:    将字符串分成小段。
convert_cyr_string:    转换古斯拉夫字符串成其它字符串。
crypt:    将字符串用 DES 编码加密。
echo:    输出字符串。
explode:    切开字符串。
flush:    清出输出缓冲区。
get_meta_tags:    抽出文件所有 meta 标记的资料。
htmlspecialchars:    将特殊字符转成 HTML 格式。
htmlentities:    将所有的字符都转成 HTML 字符串。
implode:    将数组变成字符串。
join:    将数组变成字符串。
ltrim:    去除连续空白。
md5:    计算字符串的 MD5 哈稀。
nl2br:    将换行字符转成 <br>。
Ord:    返回字符的序数值。
parse_str:    解析 query 字符串成变量。
print:    输出字符串。
printf:    输出格式化字符串。
quoted_printable_decode:    将 qp 编码字符串转成 8 位字符串。
QuoteMeta:    加入引用符号。
rawurldecode:    从 URL 专用格式字符串还原成普通字符串。
rawurlencode:    将字符串编码成 URL 专用格式。
setlocale:    配置地域化信息。
similar_text:    计算字符串相似度。
soundex:    计算字符串的读音值
sprintf:    将字符串格式化。
strchr:    寻找第一个出现的字符。
strcmp:    字符串比较。
strcspn:    不同字符串的长度。
strip_tags:    去掉 HTML 及 PHP 的标记。
StripSlashes:    去掉反斜线字符。
strlen:    取得字符串长度。
strrpos:    寻找字符串中某字符最后出现处。
strpos:    寻找字符串中某字符最先出现处。
strrchr:    取得某字符最后出现处起的字符串。
strrev:    颠倒字符串。
strspn:    找出某字符串落在另一字符串遮罩的数目。
strstr:    返回字符串中某字符串开始处至结束的字符串。
strtok:    切开字符串。
strtolower:    字符串全转为小写。
strtoupper:    字符串全转为大写。
str_replace:    字符串取代。
strtr:    转换某些字符。
substr:    取部份字符串。
trim:    截去字符串首尾的空格。
ucfirst:    将字符串第一个字符改大写。
ucwords:    将字符串每个字第一个字母改大写

阅读全文

PHP实现验证码

数字验证码



 <? 
   
/* 
    *   Filename: authpage.php 
    
*/ 
session_start();
     
//   srand((double)microtime()*1000000); 
        $authnum = $_SESSION[''authnum''];
        
//验证用户输入是否和验证码一致 
        if(isset($_POST[''authinput'']))  
        { 
                
if(strcmp($_POST[''authinput''],$_SESSION[''authnum''])==0
                        
echo "验证成功!"
                
else 
                        
echo "验证失败!"
        } 
    
        
//生成新的四位整数验证码 

    //    while(($authnum=rand()%10000)<1000);  

    ?> 
        
<form action=test4.php method=post> 
        
<table> 
                请输入验证码:
<input type=text name=authinput style="width: 80px"><br> 
                
<input type=submit name="验证" value="提交验证码"> 
                
<input type=hidden name=authnum value=<? echo $authnum?>> 
                
<img src=authimg.php?authnum=<? echo $authnum?>> 
        
</table> 
        
</form> 

阅读全文

php5.3介绍



PHP 5.3 介绍
PHP 
2008 魁北克- Ilia Alshanetsky


 
. 新版本的特性

* 兼职老版本下的代码
* 重点主要放在现有的功能的改进
* 更少的bug
* 更快的发布周期


1. 命名空间(Namespaces)

* PHP5.3最大的新功能
* 完全支持名字空间特征
* 大部分的功能的执行在编译时
* 简化命名惯例

1) 更清晰的代码

    不使用 Namespaces
    
function MY_wrapper() {}
    
class MY_DB {}
    
define(''MY_COMM_STR'', '''');

   
    MY_wrapper();
    
new MY_DB();
    MY_COMM_STR;

2) 使用 Namespaces
   
    namespace MY;
   
    
function wrapper() {}
   
    
class DB { }
   
    
const CONN_STR = '''';
           
   
    
use MY AS MY;
   
    wrapper();
   
    
new DB();
   
    CONN_STR;
   


3) 一个文件中多个名字空间
   
    namespace LIB;
   
    
class MYSQL {}
    
class SQLite {}
   
    
$b = new SQLite(;
   
    namespace LIB_EXTRA;
   
    
class MScrypt {}
   
    
$a new MScrypt();
   
    
var_dump(
        
get_class($a),
        
get_class($b)
    };
   
    
// result:
    // string(18) "LIB_EXTRA::MScrypt"
    // string(11) "LIB::SQLite"






4) 名字空间的层级

    namespace foo;
   
    
function strlen($foo) { return htmlspecialchars($foo); }
   
    
echo strlen("test"); // test
    echo ::strlen("test"// 4
    echo namespace::strlen("test"); // test
   
    
* function, class 和 constant 引用在一个名字空间中首先指向这个名字空间, 其次才是一个全局的范围


5) 名字空间 & 自动引入


    
function __autoload($var) { var_dump($var); } // LIB::foo
    require "./ns.php";
    
/**
    <?php
     namespace LIB;
     new foo();
    ?>
    
*/

* __autoload() 将处理为和名字空间的类名一起。
* autoload 仅在 class 不在名字空间和全局范围内存在时触发。
* __autoload() 声明在一个名字空间中将不别调用!




6) 其他的名字空间的语法技巧

    namespace really
::long::pointlessly::verbose::ns;
   
    __NAMESPACE__; 
// 当前的名字空间名称
   
    
class a {}
   
    
get_classnew a() ); // really::long::pointlessly::verbose::ns::abs
   
    
use really::long::pointlessly::verbose::ns::AS b; // 从一个名字空间引用class

   


2. 改进的性能
* md5() 速度提高了大概10-15%
* 引擎中更好的堆栈实现
* 常量移到只读内存区
* 改进Exception处理(更简单 & 更少的代码)
* 调用 (require/include)_once 去掉了使用open(2)(linux下的c函数)
* 使用gcc4编译的二进制更小更快

整体性能提高 
5-15%



3. 新的语言特性


1) __DIR__

* 引入 __DIR__ magic常量 定位脚本的目录

    
echo dirname(__FILE__); // < PHP 5.3
   
    
/* vs */
   
    
echo __DIR__; // >= 5.3


2?:  操作符
* 允许从2个值的or/and表达式快速的获取一个非空的值
   
    
$a = true ?: false// true;
    $a = false ?: true// true;
    $a = "" ?: 1// 1
    $a = 0 ?: 2// 2
    $a = array() ?: array(1); // array(1);
    $a = strlen(""?: strlen("a"); // 1
   



3) __callStatic()
   
    
* 等价于 __call() , 但它是为调用静态方法准备的
   
    
class helper
    {
        
static function __callStatic($name, $args){
            
echo $name.''(''.implode('','' $args).'')'';
        }       
    }
   
    helper
::test("foo", "bar"); // test(foo,bar);


// 动态的函数/方法调用有点慢...

 
 
4) 动态的调用静态方法
 
* php 现在允许 动态的调用静态的方法
   
    
class helper
    {
        
static function foo(){
            
echo __METHOD__;`
        }   
    }
   
    
$a = "helper";
    
$b = "foo";
   
    
$a::$b(); // helper::foo

// 动态的函数/方法调用有点慢...


5) 延迟静态绑定

* 静态处理从编译时延迟到执行时
   
    
class A
    {
        
public static function whoami(){
            
echo __CLASS__;   
        }
       
        
public static function identity(){
            self
::whoami();   
        }
    }
   
    
class B extends A
    {
        
public static function whoami(){
            
echo __CLASS__;
        }
    }
   
    B
::identity(); // A <-- php < 5.3
   
   
    
class A
    {
        
public static function whoami(){
            
echo __CLASS__;   
        }
       
        
public static function identity(){
            
static::whoami();   
        }
    }
   
    
class B extends A
    {
        
public static function whoami(){
            
echo __CLASS__;
        }
    }
   
    B
::identity(); // B <-- php >= 5.3
   

* 小心使用操作码缓存,没有向后兼容



6) MySQLInd

* 特殊的,高速的专门为PHP设计的MySQL调用库接口




* 更好的性能
* 内存的使用优化
* 内置的驱动(不是适应性的再次扩展)
* Many future options due to tight integration with PHP
* 目前还没有PDO_MySQL 支持 mysql(i) only for now





7) INI Magic

* CGI/FastCGI 支持".htaccess" 形式的INI控制
* 用户可以自己设定每个目录的INI在php.ini中通过[PATH=/var/www/domain.com]设定
* 优化错误处理
* 允许用户使用INI变量和常量任何定义的INI文件中
* 其他几个小的优化


    用户自定义的php
.ini(.htaccess) 文件名. 默认为".user.ini"
    user_ini
.filename = ".user.ini"


禁止这个特性 设置这个选项为空值


    用户自定义php
.ini 的缓存失效期(time-to-live) 秒数. 默认is 300s (5分钟)
    user_ini
.cache_ttl = 300s
   
    [PATH
=/var/www/domain.com]
    variables_order 
= GPC
    safe_mode 
= 1

    [my varibles]
    somevar 
= "1234"
    anothervar 
= ${somevar}    ; anothervar == somevar

    [ini arrays]
    foo[bar] 
= 1
    foo[
123= 2
    foo[] 
= 3



8) 扩展的 OpenSSL 函数

* 使用 OpenSSL Digest 函数

    
foreach (openssl_get_md_methods() as $d) {// MD4, MD5, SHA512... (12 all in all)
        echo $d. " - ". openssl_digest("foo", "md5"); // acbd18db4cc2f85cedef654fccc4a4d8
    }

* 使用 OpenSSL 加密函数

    
// BF-CBC, AES-256 CFB1... (54 all in all)
    foreach(openssl_get_cipher_methods() as $v) {
        
$val = openssl_encrypt("value", $v, "secret");
        openssl_decrypt(
$val, $v, "secret"); // value
    }


* 扩展的 openssl_pkey_new() 和 openssl_pkey_get_details()
函数 允许访问 内部的 DSA
, RSA 和 DH 密匙.


其目标在PHP中实现一个简单的OpenId


 
9) SPL(Standard PHP Library) 优化

* 优化嵌套的目录迭代次数由文件系统迭代

* 引入 GlobIterator

* 各种各样的数据结构类: 双链表, 堆栈, 队列, 堆, 小型堆, 大型堆, 优先级队列
 

* 其他的很绕口的一些特征


10) 时间处理进行扩展了和添加

* 可控制的 strtotime() 由 date_create_from_format()实现
   
    
$date = strtotime("08-01-07 00:00:00");
    
var_dump(date("Y-m-d", $date)); // string(10) "2008-01-07"
    $date = date_create_from_format("m-d-y", "08-01-07");
    
var_dump($date->format(''Y-m-d'')); // string(10) "2007-08-01"

* 添加了 date_get_last_errors(),并且返回时间语法分析的错误和警告
    
array(4) {
        [
"warning_count"=> int(0)
        [
"warnings"=> array(0) { }
        [
"error_count"=> int(2)
        [
"errors"]=>
            
array(2) {
                [
2]=> string(40"The separation symbol could not be found"
                [
6]=> string(13"Trailing data"
            }
    }


 
11) getopt() 优化

* 影响 Windows 平台

* 本地的执行不依赖于本地getopt()实现.

* 跨平台支持长选项 (--option)
    
// input: --a=foo --b --c
    var_dump(getopt("", array("a:","b::","c")));
    
/* output: array(3) {
        ["a"]=>
        string(3) "foo"
        ["b"]=>
        bool(false)
        ["c"]=>
        bool(false)
    } 
*/


 
12) XSLT Profiling
* 引入 Xslt Profiling 通过 setProfiling()实现

    
$xslt = new xsltprocessor();
    
$xslt->importStylesheet($xml);
    
$xslt->setProfiling("/tmp/profile.txt");
    
$xslt->transformToXml($dom);
   
    Resulting In
:
    
number         match     name     mode     Calls     Tot 100us Avg
        
0         date                         5         58       11
                    Total                     
5         58


 
13) E_DEPRECATED 标记
* 怎么样将一个php发行为一个没有错误的模式? 废弃

* E_DEPRECATED用来指定废弃的功能,或许未来的版本中会消除。


 
14) 垃圾回收器
* 为复杂和长时间运行脚本的执行结束周期释放内存的清理
 
        gc_enable(); 
// 允许垃圾回收
        var_dump(gc_enabled()); // true
        var_dump(gc_collect_cycles()); // 某个元素的清理
        gc_disable(); // 禁止垃圾回收
       
 
15) NOWDOC
* 一个 HEREDOC 不再进行转译

        HEREDOC
    
$foo = <<<ONE
    this is 
$fubar
    ONE;
    
/* string(10) "this is" */
   
    

阅读全文

php下过滤HTML代码的函数

*----------------------
过滤HTML代码的函数
-----------------------*/
function htmlEncode($string) {
    $string=trim($string);
    $string=str_replace("&","&",$string);
    $string=str_replace("''","''",$string);
    $string=str_replace("&amp;","&",$string);
    $string=str_replace("&quot;",""",$string);
    $string=str_replace(""",""",$string);
    $string=str_replace("&lt;","<",$string);
    $string=str_replace("<","<",$string);
    $string=str_replace("&gt;",">",$string);
    $string=str_replace(">",">",$string);
    $string=str_replace("&nbsp;"," ",$string);
    $string=nl2br($string);
    return $string;
}

阅读全文

php实现文件下载的一段代码


$file_dir=$totalDirectory;
     $file_name=$filename;
     //echo ''./db/''.$file_dir.$file_name;
    if (file_exists($file_dir.$file_name)){
          $file=fopen($file_dir.$file_name,''r'');
         Header(''Content-type:application/octet-stream'');
         Header(''Accept-Ranges:bytes'');
         Header(''Content-Disposition:attachment;filename=''.$file_name);
         echo fread($file,filesize($file_dir.$file_name));
         fclose($file);
         exit;
        
     }else{
         echo ''file is not exists'';
     }

阅读全文

php生成静态页面的简单实例


一个简单的实例:
新闻模版文件news_tmp.html:
<html>
<head>
<title>{title}</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<TABLE border=0 width=767 cellspacing="0" cellpadding="5">
  <TR>
 <TD>
      <div align="center">{news_title}</div>
    </TD>
</TR>
<TR>
 <TD>
      <div align="center">{news_image}</div>
    </TD>

阅读全文

php的数组问题

最近在做一个项目的时候发现,在php中,如果要对一个数据的某个元素进行赋值的时候,就会报错如:

<?php
$str="222222";
$var=array(
         a
=>"1",
         b
=>$str,
         c
=>""
);
if($var[b]){
       
$var[c]=$var[b];
}
?> 
会提示出错,说明未定义常量。
这种情况有俩个方法可以解决,一就是更改php.ini的配置
修改php.ini,把error_reporting        =        E_ALL改成
error_reporting        =        E_ALL    &    ~E_NOTICE
如果这种不能解决的话,
就把

 替换成


 


阅读全文

CakePHP 中文教程3


class CategoriesController extends AppController
{
    var $scaffold
;
}

有关Scaffold,要注意一个重要的问题:Scaffold期望每个以_id结尾的filed name是一个外键并且指向一个tabletable的名称和_id前方的一样(只不过是小写的)。所以,举个例子来说,如果你嵌套了分类,你最好有个列叫做parent_id。在这个版本中,最好能够命名为parentid.同样,在表中有一个外键(比如,titles table有个category_id,并且你已经合适的联结到models(查看6.2理解联结),在show/edit/newdviews中,选择的表将会和外键的表(category)一起自动的表现出来(原文:a select box will be automatically populated with the rows from the foreign table (category) in the show/edit/new views.)。在foreign model中设置$displayField来决定foreign中哪些field会被显示。继续我们的例子,category有个标题
class Title extends AppModel 
{
    var $displayField 
= ''title'';
}

第六章Models

阅读全文