PHP优化技巧

pexels-sasha-prasastika-2825384

数组去重

去除重复保证唯一

1
2
3
4
# 一般
array_unique($array);
# 高效
array_keys(array_flip($array));

数组随机值

在一个很大的数组中随机选择一个值

1
2
array_rand($array);
$array[mt_rand(0, count($array) - 1)];

检查字符串是否是字母

或数字或字母数字的组合形式

1
2
3
4
5
# 一般
preg_match('/[a-zA-Z0-9]+/', $string);
# 高效,https://www.php.net/manual/zh/function.ctype-alnum.php
ctype_alnum($string);

字符串替换

1
2
str_replace('google.com', 'nobige.cn', $string);
strtr($string, 'google.com', 'nobige.cn');

JSONP解码

1
2
3
4
5
6
7
8
function jsonp_decode($jsonp, $assoc = false) { 
// PHP 5.3 adds depth as third parameter to json_decode
if($jsonp[0] !== '[' && $jsonp[0] !== '{') {
// we have JSONP
$jsonp = substr($jsonp, strpos($jsonp, '('));
}
return json_decode(trim($jsonp,'();'), $assoc);
}

密码加密

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 一般
$_userInput = 'nobige.cn';
# md5("nobige.cn")
$_fakeDBPassword = '4fe123849e90f01b50c1e6b143562842';

if (md5($_userInput)==$_fakeDBPassword) {
echo('password is right');
// do thing
}else{
echo('password is error');
// do thing
}

# 安全,https://www.php.net/manual/zh/ref.password.php
$_userInput = 'nobige.cn';
# password_hash('nobige.cn', PASSWORD_DEFAULT)
$_fakeDBPassword = '$2y$10$YlrcIWmQWL3wxdo1AXyw9OD7PGoR8hv52WJNq0n3jDh0wzsTdWSAi';

if (password_verify($_userInput, $_fakeDBPassword)) {
echo('password is right');
// do thing
}else{
echo('password is error');
// do thing
}

换行符

根据平台而变

windows下会是/r/n

linux下是/n

mac下是/r

1
echo(PHP_EOL);

参考