Skip to content

Instantly share code, notes, and snippets.

@azhai
Last active December 19, 2015 22:18
Show Gist options
  • Save azhai/6026211 to your computer and use it in GitHub Desktop.
Save azhai/6026211 to your computer and use it in GitHub Desktop.
PHP字符串辅助函数
<?php
/**
* 表示Yes的字符串
*/
function is_yes ($word)
{
$yes_words = array(
'1','y','t','ok','yes','true','allow','agree'
);
return $word && in_array(strtolower($word), $yes_words);
}
/**
* 保留字符串中的数字
*/
function get_numbers ($word)
{
$times = preg_match_all('/[\d.]+/', $word, $matches);
if ($times === 0 || $times === false) {
return false;
}
return intval(implode(current($matches)));
}
/**
* 产生16进制随机字符串
*/
function randHash ($length = 6)
{
$length = $length > 32 ? 32 : $length;
$hash = md5(mt_rand() . time());
$buffers = substr($hash, 0, $length);
return $buffers;
}
/**
* 产生可识别的随机字符串
*/
function randString ($length = 8, $shuffles = 2, $good_letters = '')
{
if (empty($good_letters)) {
// 字符池,去掉了难以分辨的0,1,o,O,l,I
$good_letters = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
}
srand((float) microtime() * 1000000);
$buffer = '';
// 每次可以产生的字符串最大长度
$gen_length = ceil($length / $shuffles);
while ($length > 0) {
$good_letters = str_shuffle($good_letters);
$buffer .= substr($good_letters, 0, $gen_length);
$length -= $gen_length;
$gen_length = min($length, $gen_length);
}
return $buffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment