Tips:点此可运行HTML源码

札记 - PHP/JS/jQuery/MySQL/CSS/正则/Apache

PHP:

--------------------------------------------------------------------------------------------------------------------------------------------

1、Fatal error: Allowed memory size of 8388608 bytes exhausted
解决:
  方法一:修改php.inimemory_limit = 8M中的8M至合适值;(此方法设置发现失效的话请检查phpinfo定位好php.ini位置重新修改)
  方法二:在程序文件开头加入ini_set("memory_limit","32M");  //32M按需调节

 

2、cookie子域名共享
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] ) 为了使Cookie在子域名也能够生效,$domain须设置成:'.domain.com', 如博客园的设置成:'.cnblogs.com'即可。

 

3、关于echo
<?php $conn = '__'; echo 'abc'; //正确 echo "abc"; //正确 echo ('abc'); //正确 echo ("abc"); //正确 echo 'abc'.$conn.'def'; //正确 echo 'abc',$conn,'def'; //正确
// echo ('abc',$conn,'def'); //错误

 

4、关于ini文件解析
$version
= phpversion(); if ($version >= '5.3.1') { $contents = file_get_contents($filename); $contents = str_replace('_QQ_', '"\""', $contents); $strings = @parse_ini_string($contents); } else { $strings = @parse_ini_file($filename); if ($version == '5.3.0' && is_array($strings)) { foreach ($strings as $key => $string) { $strings[$key] = str_replace('_QQ_', '"', $string); } } } @example >=5.3.1 $contents = 'COM_USERS_REGISTER_REQUIRED="<strong class="_QQ_"red"_QQ_">*</strong> Required field"'; var_dump(str_replace('_QQ_', '"\""', $contents),parse_ini_string(str_replace('_QQ_', '"\""', $contents))); /* string(85) "COM_USERS_REGISTER_REQUIRED="<strong class=""\"""red""\""">*</strong> Required field"" array(1) { ["COM_USERS_REGISTER_REQUIRED"]=> string(45) "<strong class="red">*</strong> Required field" } */

 

5、解析object成string
/**
 * Converts an object into a php class string.
 * - NOTE: Only one depth level is supported.
 *
 * @param   object  $object  Data Source Object
 * @param   array   $params  Parameters used by the formatter
 *
 * @return  string  Config class formatted string
 *
 * @since   11.1
 */
public function objectToString($object, $params = array())
{
    // Build the object variables string
    $vars = '';
    foreach (get_object_vars($object) as $k => $v)
    {
        if (is_scalar($v))
        {
            $vars .= "\tpublic $" . $k . " = '" . addcslashes($v, '\\\'') . "';\n";
        }
        elseif (is_array($v) || is_object($v))
        {
            $vars .= "\tpublic $" . $k . " = " . $this->getArrayString((array) $v) . ";\n";
        }
    }

    $str = "<?php\nclass " . $params['class'] . " {\n";
    $str .= $vars;
    $str .= "}";

    // Use the closing tag if it not set to false in parameters.
    if (!isset($params['closingtag']) || $params['closingtag'] !== false)
    {
        $str .= "\n?>";
    }

    return $str;
}
/**
 * Method to get an array as an exported string.
 *
 * @param   array  $a  The array to get as a string.
 *
 * @return  array
 *
 * @since   11.1
 */
protected function getArrayString($a)
{
    $s = 'array(';
    $i = 0;
    foreach ($a as $k => $v)
    {
        $s .= ($i) ? ', ' : '';
        $s .= '"' . $k . '" => ';
        if (is_array($v) || is_object($v))
        {
            $s .= $this->getArrayString((array) $v);
        }
        else
        {
            $s .= '"' . addslashes($v) . '"';
        }
        $i++;
    }
    $s .= ')';
    return $s;
}

 

 6、多维数组排序
1
<?php 2 //多维数组按某一维进行排序 3 $data[] = array('volume' => 67, 'edition' => 2); 4 $data[] = array('volume' => 86, 'edition' => 1); 5 $data[] = array('volume' => 85, 'edition' => 6); 6 $data[] = array('volume' => 98, 'edition' => 2); 7 $data[] = array('volume' => 86, 'edition' => 6); 8 $data[] = array('volume' => 67, 'edition' => 7); 9 // 取得列的列表 10 foreach ($data as $key => $row) { 11 $volume[$key] = $row['volume']; 12 $edition[$key] = $row['edition']; 13 } 14 15 // 将数据根据 volume 降序排列,根据 edition 升序排列 16 // 把 $data 作为最后一个参数,以通用键排序 17 array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data); 18 echo '<pre>'; 19 var_dump($data); 20 ?>

 

 1 7、嵌套div解析
 2 <?php
 3     /**
 4      * 模式修饰符s,可使得.能匹配包括换行在内的任意字符
 5      * 模式修饰符i,不区分大小写匹配     
 6      * (?!<div.*?>.*<div.*?</div>) 负向预查排除<div中间还带<div的情况
 7      * <div.*?>(.*?)</div> 每次匹配一个中间不含<div的字符串
 8      */
 9     $str = '<div class="a">aaaa<div>
10     1111</div><div>
11     2222<div>3333
12     </div></div>bbbb</div>';
13     $str = '<div class="a">1111<div>2222</div>3333</div><div class="a">4444<div>5555</div>6666</div><div class="a">7777<div>8888</div><div>9999</div>aaaa</div>';
14     $str = '<div class="a">aaaa<div>1111</div><div><span>2222</span></div>bbbb</div>';
15 
16     $results = array();
17     while(preg_match('#(?!<div.*?>.*<div.*?</div>)<div.*?>(.*?)</div>#si',$str,$match,PREG_OFFSET_CAPTURE)){    //对中间不存在<div的字符串进行匹配,记录偏移量
18         $start = $match[0][1];    //$match[0][1] 为匹配字符的起始
19         $end = $match[0][1]+strlen($match[0][0]);    //匹配字符的起始($match[0][1])加上其长度(strlen($match[0][0]))
20         $str = substr($str,0,$start) . substr($str,$end);    //原来$str为 substr($str,0,$start) . $match[0][0] . substr($str,$end);现在去掉中间部分。
21         $results[] = $match[1][0];    //$match[1][0] 小括号匹配部分
22     }
23 
24     echo '<pre>';
25     print_r($results);        //匹配结果为逆序的
26     krsort($results);        //倒序排序一下
27     print_r($results);        //顺序结果
28 
29 //End_php

 

 

JS:

--------------------------------------------------------------------------------------------------------------------------------------------

 

1、为document.getElementById('xxx')扩展函数
<
input type="button" value="AddItem" id="AddItem"></input> <div id="Items"></div> <script type="text/javascript"> Element.prototype.addItem = function(value,type,args){ if(!type) type = 'div'; var obj = document.createElement(type); obj.innerHTML = value; for(var key in args){ obj.setAttribute(key,args[key]); } this.appendChild(obj); } document.getElementById('AddItem').onclick = function(){ document.getElementById('Items').addItem('ABC','span',{'class':'item','id':'Item1'}); } </script>
同理,String.prototype.fname = function(){}可以为字符串扩展函数,Array.prototype.fname = function(){}可以为数组扩展函数。

 

2、新建js正则表达式模式
 var username = 'abc';
(1)、var p = /abc/gi;
(2)、var p = eval('/'+username+'/g');
(3)、var p = new RegExp(username,'g');

 

jQuery:

--------------------------------------------------------------------------------------------------------------------------------------------

1、jQuery(function($) {}) 与 (function($){})(jQuery)的区别

   # jQuery(function($) {}) 等价于 jQuery(document).ready(function($){}))(不适用于开发插件的代码)
   # (function($){})(jQuery)等价于var fun = function($){};fun(jQuery);适用于开发插件的代码)

 

2、$("#myDiv").eq(0) 与 $("#myDiv").get(0)的区别
    # $("#myDiv").eq(0)返回的是jQuery对象,可以操作jQuery的方法、属性
    # $("#myDiv").get(0)返回的是Element对象,可以操作javascript方法、属性

 

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>防止嵌套事件传递</title>
 6 <style>
 7 .bbb{ display:none; padding-left:20px;}
 8 </style>
 9 </head>
10 
11 <body>
12 <div class="aaa">1111
13     <div class="bbb">
14         <div class="aaa">222
15             <div class="bbb">
16                 <div class="aaa">333
17                     <div class="bbb">
18                         <div class="aaa">444</div>
19                         <div class="aaa">444</div>
20                         <div class="aaa">444</div>
21                         <div class="aaa">444</div>
22                         <div class="aaa">444</div>
23                     </div>
24                 </div>
25                 <div class="aaa">333</div>
26                 <div class="aaa">333</div>
27                 <div class="aaa">333</div>
28                 <div class="aaa">333</div>
29             </div>
30         </div>
31         <div class="aaa">222</div>
32         <div class="aaa">222</div>
33         <div class="aaa">222</div>
34         <div class="aaa">222</div>
35     </div>
36 </div>
37 </body>
38 </html>
39 <script type="text/javascript" src="http://files.cnblogs.com/Zjmainstay/jquery-1.6.2.min.js"></script>
40 <script>
41 /*
42 //js版本
43 var oA=getByClass(document,'aaa');
44 for(var i=0; i<oA.length; i++){
45     oA[i].onclick=function(ev){
46         var ev=ev||window.event;
47         var oDiv=this.getElementsByTagName('div')[0];
48         if(oDiv){
49             if(oDiv.style.display=='block'){
50                 oDiv.style.display='none';
51             }else{
52                 oDiv.style.display='block';
53             }
54         }
55         ev.cancelBubble = true;
56     }
57 }
58 function getByClass(oParent,sClass){
59     var aEle=oParent.getElementsByTagName('*');
60     var arr=[];
61     var re=new RegExp('\\b'+sClass+'\\b');
62     for(var i=0; i<aEle.length; i++){
63         if( re.test(aEle[i].className) ){
64             arr.push(aEle[i]);
65         }
66     }
67     return arr;
68 }
69 // */
70 
71 // /*
72 //jQuery版本
73 $(document).ready(function(){
74     $(".aaa").click(function(event){
75         event = event || window.event;
76         event.stopPropagation();
77         if($(this).find('div').size()) {
78             if($(this).find('div:first').css('display') == 'none'){
79                 $(this).contents().show();
80             }else{
81                 $(this).contents().hide();
82             }
83         }
84     });
85 });
86 // */
87 </script>
3、防止嵌套事件传递js/jQuery解决

 

 

 

MySQL:

--------------------------------------------------------------------------------------------------------------------------------------------

 

1、mysql计算行总数
SELECT SQL_CALC_FOUND_ROWS ...
SELECT FOUND_ROWS()

 

 1 -- Mysql 多表删除语句
 2 -- 定义变量
 3 SET @tables = null;
 4 -- 拼接表名
 5 SELECT GROUP_CONCAT(table_schema, '.', table_name) INTO @tables FROM information_schema.tables 
 6 WHERE table_schema = 'test' AND table_name LIKE BINARY 'j_%';
 7 -- 拼接DROP table 语句
 8 SET @tables = CONCAT('DROP table  ', @tables);
 9 -- 删表预处理语句
10 PREPARE stmt1 FROM @tables;
11 -- 执行删表预处理语句
12 EXECUTE stmt1;
13 -- 解除预处理语句
14 DEALLOCATE PREPARE stmt1;

 

1 -- 删除重复记录
2 DELETE FROM tb_test WHERE ID NOT IN(
3     SELECT id from (
4         SELECT MAX(ID) id FROM tb_test GROUP BY CID
5     ) tmp -- delete 不能来自同名的select 表,所以此处需要添加一个tmp查询
6 )
7 
8 -- 不使用tmp查询会导致 [Err] 1093 - You can't specify target table 'TB_TEST' for update in FROM clause 报错

 

 

CSS:

--------------------------------------------------------------------------------------------------------------------------------------------

1、Zen Coding(快捷键:Ctrl+E)
    E
    元素名称(div, p);
    E#id
    使用id的元素(div#content, p#intro, span#error);
    E.class
    使用类的元素(div.header, p.error.critial). 你也可以联合使用class和idID: div#content.column.width;
    E>N
    子代元素(div>p, div#footer>p>span);
    E+N
    兄弟元素(h1+p, div#header+div#content+div#footer);
    E*N
    元素倍增(ul#nav>li*5>a);
    E$*N
    条目编号 (ul#nav>li.item-$*5);

难以区分层级的使用括号括起即可。

 

正则:

--------------------------------------------------------------------------------------------------------------------------------------------

1、汉字正则:
//js  /[\u4e00-\u9fa5]+/i 
//php /[\x7f-\xff]+/i

 

 Apache:

--------------------------------------------------------------------------------------------------------------------------------------------

RewriteEngine On

##http://test.com/htaccess/a.js        #重定向访问
##http://test.com/htaccess/a.jpg    #重定向访问
##http://test.com/htaccess/a.css    #直接访问
##http://test.com/htaccess/a.png    #直接访问
## 图片重定向
#RewriteCond %{REQUEST_FILENAME} \.(jpg|js)$
#RewriteCond %{REQUEST_URI} !^.*/local/.*$
#RewriteRule (.*) local/$1 [L]
## 等价
RewriteCond %{REQUEST_URI} !^.*/local/.*$
RewriteRule ^(.*)\.js$ local/$1.js [L,QSA]

 

1 ## .htaccess 调控文件访问顺序
2 RewriteEngine On
3 <IfModule dir_module>
4 DirectoryIndex routeIndex.php index.html index.php
5 </IfModule>
6 ## End

 

posted @ 2012-12-31 12:56 Zjmainstay 阅读(...) 评论(...) 编辑 收藏
实现请参考《为博客园添加标签云动画