您的当前位置:首页>全部文章>文章详情

php判断类

发表于:2024-04-19 13:35:44浏览:173次TAG: #PHP

前言

本文将详细介绍如何使用php对一些业务场景中的,代码逻辑中的一些条件判断,并提供整理的源码和通过示例代码进行说明。

示例

\app\common\utils\Is::mobile('15512341234');

<?php
namespace app\common\utils;
/**
 * 判断
 */
class Is {
    /**
     * 检查网络资源是否有效
     * @param string $url 网络资源url
     * @param int $timeout 检测超时时间
     * @return bool
     */
    public static function valid_assets($url,$timeout = 4) {
        // 初始化cURL会话
        $ch = curl_init($url);
        // 设置cURL选项
        curl_setopt($ch, CURLOPT_HEADER, true); // 获取头部信息
        curl_setopt($ch, CURLOPT_NOBODY, true); // 不需要body部分
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回字符串,而非直接输出
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 如果是301或302则跟随跳转
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        // 执行cURL会话
        $response = curl_exec($ch);
        // 获取HTTP状态码
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // 关闭cURL会话
        curl_close($ch);
        // 根据HTTP状态码判断文件是否有效
        return $httpCode === 200;
    }
    /**
     * 手机号码
     * @param $str
     * @return false|int
     */
    public static function mobile($str)
    {
        return preg_match("/^1[1-9]\d{9}$/",$str);
    }

    /**
     * 邮箱
     * @param $str
     * @return false|int
     */
    public static function email($str)
    {
        return preg_match("^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/",$str);
    }

    /**
     * 检查字符串中是否包含某些字符串
     * @param string       $str
     * @param string|array $needles
     * @return bool
     */
    public static function in(string $str, $needles): bool
    {
        foreach ((array) $needles as $needle) {
            if ('' != $needle && mb_strpos($str, $needle) !== false) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查字符串是否以某些字符串结尾
     *
     * @param  string       $str
     * @param  string|array $needles
     * @return bool
     */
    public static function end(string $str, $needles): bool
    {
        foreach ((array) $needles as $needle) {
            if ((string) $needle === mb_substr($str, mb_strlen($needle), null, 'UTF-8')) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查字符串是否以某些字符串开头
     *
     * @param  string       $str
     * @param  string|array $needles
     * @return bool
     */
    public static function start(string $str, $needles): bool
    {
        foreach ((array) $needles as $needle) {
            if ('' != $needle && mb_strpos($str, $needle) === 0) {
                return true;
            }
        }
        return false;
    }
}