Last active
December 19, 2015 22:18
-
-
Save azhai/6026211 to your computer and use it in GitHub Desktop.
PHP字符串辅助函数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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