乐趣区

关于php:常用的方法

 判断字符串中是否蕴含某一个字符
/**
* Determine if a given string contains a given substring.
*
* @param  string  $haystack
* @param  string|string[]  $needles
* @return bool
* 
*/
public static function contains($haystack, $needles)
    {foreach ((array) $needles as $needle) {if ($needle !== '' && mb_strpos($haystack, $needle) !== false) {return true;}
        }

        return false;
    }

Str::contains($keyword, ['_']
    /**
     * 获取客户端 IP 地址
     */
    static public function getClientIP() {
        static $ip = NULL;
        if ($ip !== NULL)
            return $ip;
        if (isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {$arr = explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] );
            $pos = array_search('unknown', $arr);
            if (false !== $pos)
                unset($arr[$pos] );
            $ip = trim($arr[0] );
        } elseif (isset( $_SERVER['HTTP_CLIENT_IP'] ) ) {$ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset( $_SERVER['REMOTE_ADDR'] ) ) {$ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP 地址非法验证
        $ip = (false !== ip2long( $ip) ) ? $ip : '0.0.0.0';
        return $ip;
    }
    /**
     * 验证手机号码
     */
    public static function mobile($str) {if ( empty( $str) ) {return true;}

        return preg_match('#^13[\d]{9}$|14^[0-9]\d{8}|^15[0-9]\d{8}$|^18[0-9]\d{8}$#', $str );
    }
/**
     * 验证身份证 (中国)
     */
    public static function idCard($str) {$str = trim( $str);
        if (empty( $str) )
            return true;

        if (preg_match( "/^([0-9]{15}|[0-9]{17}[0-9a-z])$/i", $str ) )
            return true;
        else
            return false;
    }
    /**
     * 列出文件夹列表
     *
     * @param $dirname
     * @return array
     */
    public static function getDir($dirname) {$files = array();
        if (is_dir( $dirname) ) {$fileHander = opendir( $dirname);
            while (( $file = readdir( $fileHander) ) !== false ) {
                $filepath = $dirname . '/' . $file;
                if (strcmp( $file, '.') == 0 || strcmp($file, '..') == 0 || is_file($filepath) ) {continue;}
                $files[] =  self::autoCharset( $file, 'GBK', 'UTF8');
            }
            closedir($fileHander);
        }
        return $files;
    }
    /**
     * 获取客户端 IP 地址
     */
    static public function getClientIP() {
        static $ip = NULL;
        if ($ip !== NULL)
            return $ip;
        if (isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {$arr = explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] );
            $pos = array_search('unknown', $arr);
            if (false !== $pos)
                unset($arr[$pos] );
            $ip = trim($arr[0] );
        } elseif (isset( $_SERVER['HTTP_CLIENT_IP'] ) ) {$ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset( $_SERVER['REMOTE_ADDR'] ) ) {$ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP 地址非法验证
        $ip = (false !== ip2long( $ip) ) ? $ip : '0.0.0.0';
        return $ip;
    }
退出移动版