python unicode字符串转成中文
s = 'u6d4bu8bd5u957fu5ea6'
s = s.replace('u', '\u')
print s.decode('unicode-escape')
php 二进制直接量
$bin = bindec('110011');
$bin = 0b110011;
php foreach list
$arr = [
[1, 2],
[3, 4],
];
foreach ($arr as list($a, $b)) {
echo $a.$b\n";
}
PHP ==和隐式转换
var_dump(md5('240610708') == md5('QNKCDZO'));// true 两个字符串恰好以0e 的科学记数法开头,字符串被隐式转换为浮点数,也就等效于0×10^0
var_dump(sha1('aaroZmOk') == sha1('aaK1STfY'));// true
var_dump('0x1234Ab' == '1193131');// true 0x1234Ab转为16进制,php7无此bug
var_dump( 0 == "a" );// true
var_dump( "0" == "a" );// true
== 、switch、in_array 的松比较
// 如果 $name 值为 0,那么它会满足任何一条 case
switch ($name) {// 使用switch (strval($name)) {
case "danny":
break;
case "eve":
break;
}
$needle = '1abc';
$haystack = array(1,2,3);
var_dump(in_array($needle, $haystack);// true
javascript Date对象的浏览器兼容性问题
// chrome同时支持'-'和'/'分割日期的时间字符串;safari不支持'-'分割日期的时间字符串
var arr = "2010-03-15 10:30:00".split(/[- / :]/),
date = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
javascript 模拟Object.keys()
function keys(obj){
var a = [];
for(a[a.length] in obj);
return a;
}
javascript数组去重
function dedupe(array){
return Array.from(new Set(array));
}
dedupe([1,1,2,3]) //[1,2,3]
工具
// 命令行提示tldr npm install -g tldr
octotree 是一款可为 GitHub 和 GitLab 添加侧边栏文件导航的 Chrome 和 Opera 插件
python下载视频工具
Sublime Text3 汉化
// Package Control:Install Package,输入Chinese,选择ChineseLocalization
javascript reduce
arr = [1,2,3,4,5]
arr.reduce(function(a,b){
return a*10+b;
});//12345
var result = [1, 2, 3, 4, 5].reduce(function(prev, curr, index, array){
debugger;
prev.push(curr * 2);
return prev;
}, []);
console.log(result);//[2, 4, 6, 8, 10]
//求最大值
var max = arr.reduce(function(pre,cur,inde,arr){return pre>cur?pre:cur;});
var arr = [ {name: 'brick1'}, {name: 'brick2'}, {name: 'brick3'} ]
function carryBricks(arr){
return arr.reduce(function(prev, current, index, array){
if (index === 0){
return current.name;
}
else if (index === array.length - 1){
return prev + ' & ' + current.name;
}
else {
return prev + ', ' + current.name;
}
}, '');
}//brick11, brick12 & brick13
//去重
var arr = [1, 3, 1, 'x', 'zz', 'x', false, false];
var result = arr.reduce(function(prev, curr, i, array) {
var flag = prev.every(function(value) {
return value !== curr;
});
flag && prev.push(curr);
return prev;
}, []);
console.log(result);
jquery插件
输入提示自动完成插件tokeninput
tablesorter 表格排序
Date.js执行日期/时间的计算
图片裁剪
日期选择插件pickadate.js
javascript刻度条插件
0.1+0.2
Math.round( (.1+.2)*100)/100; //0.3
mysql分解联合查询
select * from teacher
join school on teacher.id = school.id
join course on teacher.id = course.id
where course.name= 'english'
分解后
select * from course where name = 'english'
select * from school where course_id = 1
select * from teacher where school_id in (1,2,3)
字符串中每个字母重复出现的次数
var temp = {};
'abcdaabc'.replace(/(\w{1})/g,function($1){
temp[$1] ? temp[$1]+=1 : temp[$1] = 1;
})
console.log(temp) // {a: 3, b: 2, c: 2, d: 1}
composer
PHP HTTP请求套件
实现 Laravel 模型的无限极分类
php一维数组 转 多维数组
$arr = ['a', 'b', 'c', 'd'];
$child = array();
$res = [];
while($v = array_pop($arr)) {
$res = [$v => $child];
$child = $res;
}
python中字符串的按位或
a = "1000111000"
b = "1000000001"
c = int(a, 2) | int(b, 2)
print('{0:b}'.format(c))#1000111001
python生成斐波拉契数列
def fib(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
return 'done'
php正则匹配
$str="{a:1,b:2,c:3}";
preg_match_all('/(\w+):(\d+)/', $str, $matches);
$arr = array_combine($matches[1], $matches[2]);#['a'=>1,'b'=>2,'c'=>3]
php max/min
max(ceil(-0.5), 0) # -0.0
max(0, ceil(-0.5)) # 0
NaN
_.isNaN = function(obj){
return _.isNumber(obj) && obj !==+obj;
};
Mysql 用 一张表中的数据更新另一张表的数据
update tableA as ca inner join tableB as cb set ca.thumbs=cb.thumbs where cb.courseid=1;
24.php后期静态绑定
class A {
public static function get_self() {
return new self();
}
public static function get_static() {
return new static();
}
}
class B extends A {}
get_class(B::get_self());//A
get_class(B::get_static()) //B
get_class(A::get_static());//A
json_encode输出动态javascript
$images = array( 'myself.png' , 'friends.png' , 'colleagues.png' );
$js_code = 'var images = ' . json_encode($images);
echo $js_code; // var images = ["myself.png","friends.png","colleagues.png"]
String.fromCharCode
var regex_num_set = /&#(\d+);/g;
var str = "Here is some text: 每日一色|蓝白~"
str2 = str.replace(regex_num_set, function(_, $1) {
return String.fromCharCode($1);
});//"Here is some text: 每日一色|蓝白~"
日期格式补0
"2015-5-2".replace(/(?=\b\d\b)/g, '0')#"2015-05-02"
"2015-5-2".replace(/-(\d)(?=-|$)/g, '-0$1')#"2015-05-02"
array_merge如果传的参数中有一个不是数组;则返回null
$arr = [1,2,3];
$new = '';
array_merge($arr, $new);//null
array_merge($arr, (array)$new);
php switch使用的是==比较;而不是===
switch (0) {//switch (strval(0))
case 'test1':
echo 1;
case 'test2':
echo 2;
case 'test3':
echo 3;
break;
}
javascript数组的map方法对一个数组中的空位置(没有设置过值或值被删除)不会调用提供的callback回调函数
var arr=[1,,3];//第2个位置为空位置
var result=arr.map(function(x){
console.log(x);
return x + 1;//2,undefined,4
});
arr[1]=undefined;//第2个位置为非空位置,有值undefined
result=arr.map(function(x){
console.log(x);
return x + 1;//2,NaN,4
});
setTimeout传入参数
for(var i = 0; i<data.length; i++){
(function(i){
setTimeout(function (){
console.log(data[i])
},2000);
})(i)
}
//es6
for(let i = 0; i<data.length; i++){
setTimeout(function (){
console.log(data[i])
},2000);
}
循环中promise
var userIds = ['aaa', 'bbb', 'ccc'];
//这里getUserById返回的是Promise
var promises = arr.map(userIds => getUserById(userId));
Promise
.all(promises)
.then(function(users) {
console.log(users); //这里就是users的列表了
});
hasClass
function hasClass(element, cName) {
return (' ' + element.className + ' ').indexOf(' ' + cName + ' ') > -1;
}
补零
"2016-1-9 12:12:20".replace(/-(\d)(?=-|\s)/g, '-0$1')
var str = '2016-1-9 12:12:20';
var ss = str.replace(/-([0-9]+)/g, function(match, p) {
return p.length !== 1 ? match : '-0' + p;
});
getUrlParameter
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
随机数
Math.round(Math.random() * 1000)//生成0~1000之间的随机整数
((Math.random() * 10 + 5).toFixed(1) - 0)//产生一个5到15之间,包含一位小数的随机数Math.floor((Math.random() * 10 + 5) * 10) / 10
显示隐藏元素
window.onload=function(){
var li=document.getElementsByTagName("li");
for(var j=0;j<li.length;j++){
li[j].onclick=function (){
for(var i=0;i<li.length;i++){
li[i].className='';
}
this.className='a';
}
}
};
判断一个json对象中是否含有某个key
function find (obj, key) {
if (! typeof obj === 'object') return false;
if (key in obj) return true;
for (var k in obj) if find(obj[k], key) return true;
return false;
}
数组合并
array = [[1,2,3],[4,5,6],[7,8,9]];
array=array.reduce(function(a,b){return a.concat(b)})//[1,2,3,4,5,6,7,8,9]
array.concat.apply([], array);
区间索引
function getRangeIndex(scrollTop) {
var i=0;
ranges = [2,3,6,22,88];
for (;i<ranges.length;i++)
if (scrollTop<ranges[i]) break;
return i-1;
}
快速生成一个数组,数组的元素是前N个自然数
let f = length => Array.from({length}).map((v,k) => k);
let f = length => [...Array.from({length}).keys()]
let fn = len => Object.keys(new Array(len + 1).join(','))
每取10行放到一个新的文件中
with open('file.txt') as reader, open('newfile.txt', 'w') as writer:
for index, line in enumerate(reader):
if index % 10 == 0:
writer.write(line)
按首字母排序
var arr = [9,8,7,6,5,1,'在', '我', '里', '阿','z','a','h','m'];
arr.sort(function(a,b){return a.toString().localeCompare(b)}) //[1, 5, 6, 7, 8, 9, "阿", "里", "我", "在", "a", "h", "m", "z"]
删除字符串的空格
$str=' Controllable Eu valence for photoluminescence tuning in apatite-typed';
//pC:所有的unicode“other” pZ:所有的unicode“separator” ,所有空格和不可见字符
echo $str = preg_replace('/^[\pZ\pC]+|[\pZ\pC]+$/u','',$str);//Controllable Eu valence for photoluminescence tuning in apatite-typed
PHP解析JSON得到科学计数法后的int
$json = '{"number": 12345678901234567890}';
var_dump(json_decode($json,1));//[ "number" => 1.2345678901235e+19]
var_dump(json_decode($json,1, 512, JSON_BIGINT_AS_STRING));//["number" => "12345678901234567890"]
//http://cn2.php.net/manual/zh/function.json-decode.php
MySQL中所有数据库的数据大小
SELECT table_schema, (
(
SUM( DATA_LENGTH ) + SUM( INDEX_LENGTH )
) /1024 /1024
) AS datasize
FROM `TABLES`
GROUP BY table_schema
LIMIT 0 , 30
合并数组
//一般会用Array.prototype.concat()函数,但不适合来合并两个大型数组,会消耗大量内存来存储新创建的数组。可用Array.prototype.push来替代创建一个新数组,可减少内存的使用。
var array1 = [1,2,3];
var array2 = [4,5,6];
console.log(array1.push.apply(array1, array2)); // [1,2,3,4,5,6];
console.log(array1.push.call(array1, array2)); // [1,2,3,[4,5,6]];
php上传文件
$tmp_name='test.jpg';
if(version_compare(phpversion(),'5.5.0') >= 0 && class_exists('CURLFile')){
$fields['file'] = new CURLFile(realpath($tmp_name));
}else{
$fields['file'] = '@'.$tmp_name;//加@符号curl就会把它当成是文件上传处理
}
php stdclass
$tanteng = new stdClass();
$tanteng->name = 'tanteng';
$tanteng->email = 'xxx@qq.com';
//把定义的对象『转换』成数组
$info = get_object_vars($tanteng);
$user = new stdClass();
$user->name = 'gouki';
$user->hehe = 'hehe';
$myUser = $user;
$myUser->name = 'flypig';
//$myUser的属性确实改变了$user声明的stdClass属性。而如果$user是一个数组,赋值给$myUser,那就拷贝了一个副本给$myUser,这样增大系统开销
print_r($user);
print_r($myUser);
print_r($user);
PHP浮点数运算精度
$a = 69.1;
$b = $a*100;
$c = $b-6910;//-9.0949470177293E-13
$c = round($b)-6910;
$x = 8 - 6.4; // which is equal to 1.6
$y = 1.6;
var_dump($x == $y); // is not true
var_dump(round($x, 2) == round($y, 2)); // this is true
$a = intval( 0.58*100 );//57
$b = 0.58*100;
$a = intval( (0.58*1000)/10 );//58
intval( round(0.58*100 ));//58
防止浏览器屏蔽window.open
<button onclick=“test()”>点击</button>
<script>
function test(){
var frame=window.open(“about:blank”,“_blank”);
$.get(“/”,function(){
frame.location=“http://www.baidu.com”;
});
}
</script>
修改session_id的保存位置
session_set_cookie_params(0,‘/’,‘testdomain’);
session_start();//开启session
echo ‘Old Session id:’.session_id().‘<br>’;
session_regenerate_id(true);//重置session_id,并使原session无效
echo ‘New Session id:’.session_id().‘<br>’;
//echo session_id()失效
setcookie(session_name(),session_id(),0,‘/’,‘testdomain’);//手动更新session_id
CRUL命令简单分析请求细节所占用的时间
curl -o /dev/null -s -w %{http_code}:%{time_namelookup}:%{time_redirect}:%{time_pretransfer}:%{time_connect}:%{time_starttransfer}:%{time_total}:%{speed_download} www.baidu.com
//这个例子是分析一次百度的请求各个参数:http状态码、DNS解析时间、重定向时间、从开始到准备传输的时间、TCP连接时间、开始传输时间、总时间、下载速度CURL文档:https://curl.haxx.se/docs/manpage.html
php上周时间
echo '<br>上周起始时间:<br>';
echo date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1-7,date("Y"))),"\n";
echo date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7-7,date("Y"))),"\n";
echo date("Y-m-d",strtotime('-1 week last monday'))." 00:00:00";
echo date("Y-m-d",strtotime('last sunday'))." 23:59:59";
//当前时间的上一周时间 每周时间固定为7天
date('Y-m-d', strtotime('-1 week'))
//如果当前日期为2016-5-31, 用date('Y-m-d', strtotime('-1 month'))会产生错误。因为这里把 -1 month按照-30 days来算
date('Y-m-d', strtotime('2016-05-31 -1 month')) = 2016-05-01
date('Y-m-d', strtotime('2016-01-31 +1 month')) = 2016-03-02
//如果需要取当前月的前后月份的话,需要小心,正确做法可以改为
date('m', strtotime(date('Y-m-1').' -1 month'))
date('m', strtotime(date('Y-m-1').' +1 month'))
{ "a":"1","b":"2"} 变成 "a:1;b:2"
var obj = {"a":"1","b":"2","c":"3"};
var str = $.map(obj,function(n,index){return ''+index+':'+n;}).join(';');//"a:1;b:2;c:3"
var str = JSON.stringify(obj).replace(/"|{|}/g, "").replace(/,/g, ";")
Object.keys({"a":"1","b":"2"}).map(function(key){return key+':'+info[key]}).join(';');
python格式化
ips = (
(1, '10.121.1.1:4730'),
(2, '127.0.0.1:4730'),
(3, '127.0.0.1:4730')
)
dic = {}
for v, k in ips:
dic.setdefault(k, []).append((v, k))
print dic
{
'10.121.1.1:4730':
[(1, '10.121.1.1:4730')],
'127.0.0.1:4730':
[(2, '127.0.0.1:4730'), (3, '127.0.0.1:4730')]
}
PHP生成连续数据
$numbers = array(0, 1, 3, 5, 6, 8, 10);
sort($numbers);
$new = range(array_shift($numbers),end($numbers));//[0 1 2 3 4 5 6 7 8 9 10]
$a = [0,1,3,5,6,8,10];//原始数据
sort($a);
range(array_shift($a),array_pop($a));
javascript对象复制
function clone(e) {
var t = {};
for (var n in e) e.hasOwnProperty(n) && (t[n] = e[n]);
return t;
}
过滤掉emoji表情
function filterEmoji($str)
{
$str = preg_replace_callback(
'/./u',
function (array $match) {
return strlen($match[0]) >= 4 ? '' : $match[0];
},
$str);
return $str;
}
javascript选择器
function $(selector, context) {
context = context || document;
var elements = context.querySelectorAll(selector);
return Array.prototype.slice.call(elements);
};
jquery对象对比,开发中要尽量先保存创建的jQuery对象,然后多次使用
var elem1 = $("#navList li");
var elem2 = $("#navList li");
elem1 ==elem2;//false
//应该比较dom本身不是 jQuery对象
$('div') === $('div') //false
$('div')[0] === $('div')[0]//true
for 循环和异步调用的问题
for (var i = 0; i < 6; i++) {
// do 同步执行,里面的 i 是 0
do(i).then(function() {
// another 异步执行,此时 i 已经是循环后的6
another(i)
})
}
//使用闭包保存变量的方式来解决
for (var i = 0; i < 6; i++) {
// 立即执行函数作闭包,保存变量i为index
(function(index) {
do(index).then(function() {
another(index);
})
})(i)
}
按照字母和数字的顺序进行排序
var arr = ['A1','A2','A100','A7','B2','A10','A14','B12','C1','C10','C5']
arr.sort(function(a, b) {
var ret = a.charCodeAt(0) - b.charCodeAt(0); // 首字母处理
if (ret == 0) {
ret = +a.slice(1) - +b.slice(1); // 数字处理
}
return ret;//["A1", "A2", "A7", "A10", "A14", "A100", "B2", "B12", "C1", "C5", "C10"]
});
JSON.parse转换报错
var getValue = function (objStr) {
return new Function("return " + objStr)()
}
// 调用
var res1 = getValue('{"foo" : 1, }')//Object {foo: 1}
JSON.parse(res1);
javascript正则替换
var str = 'abc{xdf}efg{dfg}ijk{232}';
var arr = ['d', 'h', 'l'];
var result = str.match(/\{.*?\}/g);
for (var i = 0; i < result.length; i++) {
str = str.replace(result[i], arr[i])
}
console.log(str);
//abcdefghijkl
javascript闭包
function Score(){
this.scores = [];
}
Score.prototype.add = function(score){
this.scores.push(score);
};
Score.prototype.showAverage = function(){
let sum = this.scores.reduce(function(pre,cur){
return pre+cur;
});
console.log(sum*1.0/this.scores.length);
};
let scores = [90,80,70];
let score1 = new Score();
scores.forEach(score1.add);//scores.forEach(score1.add.bind(score1));
scores.forEach(function(score) {
score1.add(score);
});
score1.showAverage();
javascript array reduce()
arr.reduce(function (pre, cur, index) {
if (index >= 3) {
return pre;
}
return pre + cur;
}, initVal);
javascript 汉字占2字节
function getLength(str) {
return str.replace(/[^ -~]/g, 'AA').length;
}
function limitMaxLength(str, maxLength) {
var result = [];
for (var i = 0; i < maxLength; i++) {
var char = str[i]
if (/[^ -~]/.test(char))
maxLength--;
result.push(char);
}
return result.join('');
}
隐藏手机号
echo substr_replace ('13412343312','****',3,4) ;//134**3312
javascript数组降维
var flatten = function(array) {
return array.reduce(function(previous, i) {
if (Object.prototype.toString.call(i) !== '[object Array]') {
return (previous.push(i), previous);
}
return (Array.prototype.push.apply(previous, flatten(i)), previous);
}, []);
};
undefined
flatten([[1, 2],[3, 4, 5], [6, 7, 8, 9,[11,12,[12,13,[14]]]],10]);
//[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 12, 13, 14, 10]
[[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
return a.concat(b);
});
获取content-type
//获取content-type
function getContentType($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
return $contentType;
}
//获取url后缀
function getUrlExtension($url)
{
$parseurl = parse_url($url);
$extension = pathinfo($parseurl['path'], PATHINFO_EXTENSION);
return $extension;
}
PHP随机合并数组并保持原排序
//随机合并两个数组元素,保持原有数据的排序不变(即各个数组的元素在合并后的数组中排序与自身原来一致)
function shuffleMergeArray() {
$mergeArray = array();
$sum = count($array1) + count($array2);
for ($k = $sum; $k > 0; $k--) {
$number = mt_rand(1, 2);
if ($number == 1) {
$mergeArray[] = $array2 ? array_shift($array2) : array_shift($array1);
} else {
$mergeArray[] = $array1 ? array_shift($array1) : array_shift($array2);
}
}
return $mergeArray;
//合并前的数组:
$array1 = array(1, 2, 3, 4);
$array2 = array('a', 'b', 'c', 'd', 'e');
//合并后的数据:
$mergeArray = array (
0 => 'a',
1 => 1,
2 => 'b',
3 => 2,
4 => 'c',
5 => 'd',
6 => 3,
7 => 4,
8 => 'e',
)
仿知乎复制文本自带版权声明
document.body.addEventListener('copy', function (e) {
if (window.getSelection().toString() && window.getSelection().toString().length > 42) {
setClipboardText(e);
alert('商业转载请联系作者获得授权,非商业转载请注明出处,谢谢合作。');
}
});
function setClipboardText(event) {
var clipboardData = event.clipboardData || window.clipboardData;
if (clipboardData) {
event.preventDefault();
var htmlData = ''
+ '著作权归作者所有。<br>'
+ '商业转载请联系作者获得授权,非商业转载请注明出处。<br>'
+ '作者:DIYgod<br>'
+ '链接:' + window.location.href + '<br>'
+ '来源:Anotherhome<br><br>'
+ window.getSelection().toString();
var textData = ''
+ '著作权归作者所有。\n'
+ '商业转载请联系作者获得授权,非商业转载请注明出处。\n'
+ '作者:DIYgod\n'
+ '链接:' + window.location.href + '\n'
+ '来源:Anotherhome\n\n'
+ window.getSelection().toString();
clipboardData.setData('text/html', htmlData);
clipboardData.setData('text/plain',textData);
}
}
根据用户积分判断等级
//lv1:1~50
//lv2:51~110
//lv3:111~180
//lv4:181~260
function getLevel($point) {
$level = 0;
while($point >= 0) {
$point -= 50 + $level++ * 10;
}
return $level;
}
0000000序列递增
for ($i = 0; $i < 100; $i++) {
$zero = '';
$k = 7-strlen($i);
for ($j = $k; $j >0; $j--) {
$zero .= 0;
}
echo $zero.$i.'<br>';
}
for (var i = 0 ; i <= 100; i ++){
var zero = "";
for (var j = 7-i.toString().length; j > 0; j--) {
zero += "0";
}
console.log(zero + i);
}
for ($i=0;$i<=9999999;$i++) echo str_pad($i,7,"0",STR_PAD_LEFT);
//Array.from(Array(1000000).keys()).map(function(x){ return "0".repeat(8 - ("" + (x + 1)).length) + (x+1)})
判断远程图片是否存在
function exist_file($url){
$opts=array(
'http'=>array(
'method'=>'HEAD',
'timeout'=>2
));
@file_get_contents($url,false,stream_context_create($opts));
if ($http_response_header[0] == 'HTTP/1.1 200 OK') {
return true;
} else {
return false;
}
}
检测函数类型
function getType(value){ //基本上可以返回所有的类型,不论你是自定义还是原生
return Object.prototype.toString.call(value).match(/\s{1}(\w+)/)[1];
}
let obj = new Object();
console.log(getType(obj)); //"Object"
moment.js时间处理
var a = moment([2016, 0, 15]);
var b = moment([2016, 7, 31]);
var diff = b.diff(a, 'months');
var diffMonths = Array
.apply([], new Array(diff + 1))
.map(function(item, index) {
return a.clone().add(index, 'month').format('YYYY-MM');
});
console.log(diffMonths);//["2016-01", "2016-02", "2016-03", "2016-04", "2016-05", "2016-06", "2016-07"]
php中文正则匹配
php中文正则匹配$str = "one中国你好two";
$preg = "/\P{Han}+/u";
$result = preg_replace($preg, '', $str);
var_dump($result); //string(12) "中国你好" p小写是匹配汉字,P大写是匹配非汉字
生成6位的数字验证码
console.log(('000000' + Math.floor(Math.random() * 999999)).slice(-6));
console.log(Math.random().toString().slice(-6));
console.log(/\d{6}/.exec(Math.random())[0])
console.log('' + Math.floor(Math.random() * 999999));
16进制颜色代码生成
(function(){
return '#'+('00000'+(Math.random()*0x1000000<<0).toString(16)).slice(-6);
})()
php 模拟 tail -f
$handle = popen("tail -f /var/log/nginx/access.log 2>&1", 'r');
while(!feof($handle)) {
$buffer = fgets($handle);
echo "$buffer\n";
flush();
}
pclose($handle);
mysql distinct
test表的结构
id test1 test2
1 a 1
2 a 2
3 a 3
4 a 1
5 b 1
6 b 2
7 b 3
8 b 2
select distinct test1 from test
test1
a
b
select distinct test1, id from test
test1 id
a 1
a 2
a 3
a 4
b 5
b 6
b 7
b 8
SELECT id, group_concat( DISTINCT test1 ) t FROM test GROUP BY test1
id t
1 a
5 b
php下载文件
try {
$client = new \GuzzleHttp\Client($url,[
'curl.options' => [
CURLOPT_SSL_VERIFYPEER=>2,
CURLOPT_SSL_VERIFYHOST=true,
]
]);
$data = $client->request('get','http://xxxx')->getBody()->getContents();
Storage::disk('local')->put('filename', $data);
} catch (\GuzzleHttp\RequestException $e) {
echo 'fetch fail';
}
javascript sort 排序
var arr=[3,4,6,21,2,3,4,1,2,9,6,3,4,5,6,7,2,3];
arr.sort(function(a,b){
return a>b;
});
console.log(arr);//[9, 3, 2, 3, 2, 3, 2, 1, 3, 4, 4, 4, 5, 6, 6, 6, 7, 21]
var arr=[3,4,6,21,2,3,4,1,2,9,6,3,4,5,6,7,2,3];
arr.sort(function(a,b){
return a-b;
});
console.log(arr);//[1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 9, 21]
var arr=[
{name:"one",age:10},
{name:"two",age:40},
{name:"three",age:30},
{name:"four",age:90},
{name:"five",age:60}
];
arr.sort(function(a,b) {
return a.age-b.age;
});
console.log(arr);
javascript date
new Date(2016,1,31) > new Date(2016, 2, 1)//true
//month 从 0 开始算 new Date(2016,1,31) == 2016 年 2 月 31 日 然而 2 月只有 29 天 so
new Date(2016,1,31) == 2016 年 3 月 2 日
new Date(2016,1,30) > new Date(2016, 2, 1)//false
javascript lastIndex
function filtrate() {
var newArr = [], reg = /^\s*$/g,
str = "baidu,google, , ,baidu,google,bg";
arr = str.split(',');
for (var i = 0; i < arr.length; i++) {
//var reg = /^\s*$/g;
if (!reg.test(arr[i])) {
newArr.push(arr[i]);
}
}
return newArr;//["baidu", "google", " ", "baidu", "google", "bg"]
}
function filtrate2() {
var newArr = [], reg = /^\s*$/g,
str = "baidu,google, , ,baidu,google,bg";
arr = str.split(',');
for (var i = 0; i < arr.length; i++) {
var reg = /^\s*$/g;
if (!reg.test(arr[i])) {
newArr.push(arr[i]);
}
}
return newArr; //["baidu", "google", "baidu", "google", "bg"]
}
微信浏览器禁止页面下拉查看网址
var overscroll = function(el) {
el.addEventListener('touchstart', function() {
var top = el.scrollTop
, totalScroll = el.scrollHeight
, currentScroll = top + el.offsetHeight;
//If we're at the top or the bottom of the containers
//scroll, push up or down one pixel.
//
//this prevents the scroll from "passing through" to
//the body.
if(top === 0) {
el.scrollTop = 1;
} else if(currentScroll === totalScroll) {
el.scrollTop = top - 1;
}
});
el.addEventListener('touchmove', function(evt) {
//if the content is actually scrollable, i.e. the content is long enough
//that scrolling can occur
if(el.offsetHeight < el.scrollHeight)
evt._isScroller = true;
});
}
overscroll(document.querySelector('.scroll'));
document.body.addEventListener('touchmove', function(evt) {
//In this case, the default behavior is scrolling the body, which
//would result in an overflow. Since we don't want that, we preventDefault.
if(!evt._isScroller) {
evt.preventDefault();
}
});
laravel 为 VerifyCsrfToken 添加过滤条件
//修改 app/Http/Middleware/VerifyCsrfToken.php
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
use Closure;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
public function handle($request, Closure $next)
{
// 如果是来自 api 域名,就跳过检查
if ($_SERVER['SERVER_NAME'] != config('api.domain'))
{
return parent::handle($request, $next);
}
return $next($request);
}
}
switch 字符串和数字会隐式转换比较
$string="2string";
switch($string)
{
case (string) 1:
echo "this is 1";
break;
case (string) 2:
echo "this is 2";
break;
case '2string':
echo "this is a string";
break;
}
输出调试信息
function log(msg){
var $body = document.querySelector('body');
if( !$body.querySelector('.info_wz_852') ){
$body.innerHTML += '<div class="info_wz_852" style="position:fixed;top:0;left:0;z-index:99999; background:#000;color:#f00;"></div>';
}
var $info = $body.querySelector('.info_wz_852');
var date = new Date(),
minute = ('00'+date.getMinutes()).slice(-2),
second = ('00'+date.getSeconds()).slice(-2);
try{
throw new Error();
}catch(e){
var loc = (e.stack.replace(/Error\n/).split(/\n/)[1]).replace(/^(\s|\u00A0)+/,'').replace(/(\s|\u00A0)+$/,'');
// var arr = loc.split(':'),
// col = parseInt(arr.pop()),
// line = parseInt(arr.pop());
$info.innerHTML += '<p>['+minute+':'+second+'] '+loc+'</p><p>'+msg+'</p><br/>';
}
}
对象数组互转方法
/**
* 数组转换对象
*
* @param $arr 数组
* @return object|void
*/
public function arrayToObject($arr)
{
if (gettype($arr) != 'array') return;
foreach ($arr as $k => $v) {
if (gettype($v) == 'array' || getType($v) == 'object')
$e[$k] = (object)$this->arrayToObject($v);
}
return (object)$e;
}
/**
* 对象转换数组
*
* @param $e StdClass对象实例
* @return array|void
*/
public function objectToArray($s)
{
$s = (array)$s;
foreach ($s as $k => $v) {
if (gettype($v) == 'resource') return;
if (gettype($v) == 'object' || gettype($v) == 'array')
$e[$k] = (array)$this->objectToArray($v);
}
return $e;
}
javascript数组随机
Array.prototype.shuffle = function(n) {
var len = this.length , num = n?Math.min(n,len):len,arr = this.slice(0)
arr.sort(function(a,b){
return Math.random()-0.5
})
return arr.slice(0,num-1)
}
php生成不重复字符串
echo sprintf('%x',crc32(microtime()));
PHP 随机用户名账号
//循环创建1万个随机账号,0碰撞,10万大约0-3个碰撞,足够应付未来数十亿级PV
function genUserNumber()
{
$chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$username = "";
for ( $i = 0; $i < 6; $i++ )
{
$username .= $chars[mt_rand(0, strlen($chars))];
}
return strtoupper(base_convert(time() - 1420070400, 10, 36)).$username;
}
一个操作中对 Redis 服务器执行多个命令
Redis::pipeline(function ($pipe) {
for ($i = 0; $i < 1000; $i++) {
$pipe->set("key:$i", $i);
}
});
中文拼音排序
from pypinyin import lazy_pinyin
chars = ['鑫','鹭','榕','柘','珈','骅','孚','迦','瀚','濮','浔','沱','泸','恺','怡','岷','萃','兖']
chars.sort(key=lambda char: lazy_pinyin(char)[0][0])
print([lazy_pinyin(char) for char in chars])
print(chars)
[['cui'], ['fu'], ['hua'], ['han'], ['jia'], ['jia'], ['kai'], ['lu'], ['lu'], ['min'], ['pu'], ['rong'], ['tuo'], ['xin'], ['xun'], ['yi'], ['yan'], ['zhe']]
['萃', '孚', '骅', '瀚', '珈', '迦', '恺', '鹭', '泸', '岷', '濮', '榕', '沱', '鑫', '浔', '怡', '兖', '柘']
php 金额每三位加逗号分隔
//money_format
>>> strrev(implode(',', str_split(strrev('434353222323443'), 3)) )
=> "434,353,222,323,443"
php时间格式化
function getDiffTime($timestamp)
{
$datetime = new DateTime(date('Y-m-d H:i:s', $timestamp));
$datetime_now = new DateTime();
$interval = $datetime_now->diff($datetime);
list($y, $m, $d, $h, $i, $s) = explode('-', $interval->format('%y-%m-%d-%h-%i-%s'));
if ((($result = $y) && ($suffix = '年前')) ||
(($result = $m) && ($suffix = '月前')) ||
(($result = $d) && ($suffix = '天前')) ||
(($result = $h) && ($suffix = '小时前')) ||
(($result = $i) && ($suffix = '分钟前')) ||
(($result = $s) && ($suffix = '刚刚'))) {
return $suffix != '刚刚' ? $result . $suffix : $suffix;
}
}
html写入word
function word($data,$fileName=''){
if(empty($data)) return '';
$data='<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">'.$data.'</html>';
if(empty($fileName)) $fileName=date('YmdHis').'.doc';
$fp=fopen($fileName,'wb');
fwrite($fp,$data);
fclose($fp);
}
$str = '<h2>hello daye</h2>';
word($str);
一行代码可以看到所有页面元素
[].forEach.call($$("*"),function(a){a.style.outline="1px solid #"+(~~(Math.random()*(1<<24))).toString(16)})
https://segmentfault.com/a/11...
http://blog.tanteng.me/2015/1...
http://joebon.cc/date-cross-b...
https://segmentfault.com/a/11...
https://segmentfault.com/q/10...
https://www.zhihu.com/questio...
http://t.cn/RqgIMWa
http://t.cn/h4tDfg
http://div.io/topic/1610
https://www.talkingcoder.com/...
http://www.w3cfuns.com/notes/...
http://www.cnblogs.com/shocke...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。