字符串

  1. 正则视频推荐

  2. 输出格式化

    # 函数列表
    sprintf()
    fprintf()
    printf()
    vfprintf()
    vprintf()
    vsprintf()
    
    # 格式列表
    %% - 返回一个百分号 %
    %b - 二进制数
    %c - ASCII 值对应的字符
    %d - 包含正负号的十进制数(负数、0、正数)
    %e - 使用小写的科学计数法(例如 1.2e+2)
    %E - 使用大写的科学计数法(例如 1.2E+2)
    %u - 不包含正负号的十进制数(大于等于 0)
    %f - 浮点数(本地设置)
    %F - 浮点数(非本地设置)
    %g - 较短的 %e 和 %f
    %G - 较短的 %E 和 %F
    %o - 八进制数
    %s - 字符串
    %x - 十六进制数(小写字母)
    %X - 十六进制数(大写字母)
    %m.nf - 数字最高取m位,其中小数部分n位
    
  3. sprintf()小数格式化注意以下条件

    1. 小数格式化基本格式: %m.nf - 数字最多取m位,其中小数部分n位,举例: $init_float = sprintf('%7.4f', 987.654321);//(返回值为987.6543)
    2. 四舍五入原则: 当小数位所取位数的下一位被去除时,舍去位四舍五入,举例: $init_float = sprintf('%4.1f', 987.654321);//(0.65中的5被去除,5入进1,返回值为987.7)
    3. 小数位确定原则: 小数位如果不指定,则小数部分无论如何都会保证与参数中指定的小数部分位数一致,举例: $init_float = sprintf('%4.1f', 987.654321);//(小数部分一定是1位,返回值为987.7)
    4. 小数位默认原则: 小数位如果不指定,大部分PHP版本默认取6位,不同的PHP版本与不同的操作系统小数位可能是6以外的数值,举例: $init_float = sprintf('%10.f', 987.6543);//(没有指定小数位总数,则小数位取6位,返回值为987.654300)
    5. 数值最精简原则: 数值格式化的结果会尽量取最小的位数,即使你指定了一个较大的位数,举例: sprintf('%20.2f', 999.6);//(想要小数部分2位,数字总共20位,但是999.60这个5位数字结果已经足以表示这个数字,所以不会显示一个20位的数字)
    6. 数据准确优先原则: 当为了保证数字的数值准确,数字总位数可以超过m,举例: $init_float = sprintf('%5.2f', 999.997);//(0.997中的7被去除,7入进1,0.997变为1.00,加上整数部分999为1000,为保证小数部分2位,且数值准确,结果总位数超过了5,变成了6位:1000.00)
  4. 一个英文字母、中文汉字在不同编码(字符集)下占用的字节数

    英文字母:
    字节数 : 1;编码:ISO-8859-1
    字节数 : 1;编码:GB2312
    字节数 : 1;编码:GBK
    字节数 : 1;编码:GB18030
    字节数 : 2;编码:UTF-16BE
    字节数 : 2;编码:UTF-16LE
    字节数 : 1;编码:UTF-8
    字节数 : 4;编码:UTF-16
    
    中文汉字:
    字节数 : 1;编码:ISO-8859-1
    字节数 : 2;编码:GB2312
    字节数 : 2;编码:GBK
    字节数 : 2;编码:GB18030
    字节数 : 2;编码:UTF-16BE
    字节数 : 2;编码:UTF-16LE
    字节数 : 3;编码:UTF-8
    字节数 : 4;编码:UTF-16
    
  5. PHP获取手机号归属地

    http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=[手机号]
    
  6. PHP获取字符串编码,并转为UTF-8

    <?php
    $str = '这是一个字符串';
    $str_encode = mb_detect_encoding($str);
    if($str_encode != 'UTF-8'){
    $str = iconv($str_encode, 'UTF-8', $str);
    }
    echo $str;
    
  7. UUID获取(先看php安装uuid扩展一节)

    <?php
    $uuid = uuid_create();
    
  8. php判断第四代身份证18位身份证号码最后一位是否正确

    <?php
    $id_num = '13333320001111222x';
    $sum = 0;
    $pow = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    for ($i = 0; $i < 17; $i++) {
       $num = (int)substr($id_num, $i, 1);
       $sum += $num * $pow[$i];
    }
    $end = (12 - ($sum % 11)) % 11;
    $end = $end < 10 ? (string)$end : 'x';
    echo $end;
    
  9. php判断客户端设备信息

    <?php
    $phone = '/android|webos|iphone|ipad|ipod|blackberry|symbianos|windows phone/';
    $public = '/micromessenger/';
    
    $use_type = strtolower($_SERVER['HTTP_USER_AGENT']);
    if (preg_match($phone, $use_type)) {
    echo '是手机';
    }elseif(preg_match($public, $use_type)){
    echo '公众号';
    } else {
    echo '是电脑';
    }
    
  10. php获取ip地址不能获取返回0.0.0.0

    <?php
    function getIP()
    {
    if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), '0.0.0.0')) {
    $ip_addr = getenv('HTTP_CLIENT_IP');
    } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), '0.0.0.0')) {
    $ip_addr = getenv('HTTP_X_FORWARDED_FOR');
    } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), '0.0.0.0')) {
    $ip_addr = getenv('REMOTE_ADDR');
    } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], '0.0.0.0')) {
    $ip_addr = $_SERVER['REMOTE_ADDR'];
    }else{
    $ip_addr = '0.0.0.0';
    }
    preg_match("/[\d\.]{7,15}/", $ip_addr, $ip_matches);
    $ip_addr = empty($ip_matches[0]) ? '0.0.0.0' : $ip_matches[0];
    return $ip_addr;
    }
    
  11. php获取一级域名

    <?php
    function getFirstDomain(string $domain)
    {
    $domain = preg_replace('/^(.*)?:\/\//', '', $domain);
    $domain_arr = explode(':', $domain);
    $domain = $domain_arr[0];
    $is_ip = filter_var($domain, FILTER_VALIDATE_IP);
    if ($is_ip) {
    return $domain;
    }
    $domain = trim($domain, '.');
    $domain_arr = explode('.', $domain);
    if (count($domain_arr) === 1) {
    $domain = $domain_arr[0];
    } else {
    $domain_arr = array_reverse($domain_arr);
    $domain = $domain_arr[1] . '.' . $domain_arr[0];
    }
    return $domain;
    }
    
  12. php获取上级域名

    <?php
    function getParentDomain(string $domain)
    {
        $domain = preg_replace('/^(.*)?:\/\//', '', $domain);
        $domain_arr = explode(':', $domain);
        $domain = $domain_arr[0];
        $is_ip = filter_var($domain, FILTER_VALIDATE_IP);
        if ($is_ip) {
            return $domain;
        }
        $domain = trim($domain, '.');
        $domain_arr = explode('.', $domain);
        if (count($domain_arr) === 1) {
            $domain = $domain_arr[0];
        } else {
            array_shift($domain_arr);
            $domain = implode('.', $domain_arr);
        }
        return $domain;
    }
    
  13. php获取自定义级别域名

    <?php
    function getCustomDomain(string $domain, int $custom)
    {
        $domain = preg_replace('/^(.*)?:\/\//', '', $domain);
        $domain_arr = explode(':', $domain);
        $domain = $domain_arr[0];
        $is_ip = filter_var($domain, FILTER_VALIDATE_IP);
        if ($is_ip) {
            return $domain;
        }
        $domain = trim($domain, '.');
        $domain_arr = explode('.', $domain);
        $domain_type = count($domain_arr);
        $custom = (empty($custom) || $custom < 1) ? 2 : $custom;
        if ($domain_type === 1 || $custom === 1) {
            $domain = end($domain_arr);
        } elseif ($domain_type < $custom) {
            $domain = implode('.', $domain_arr);
        } elseif ($domain_type >= $custom) {
            $domain_arr = array_slice($domain_arr, $domain_type - $custom, $custom);
            $domain = implode('.', $domain_arr);
        }
        return $domain;
    }
    
  14. php字符串类型判断

    <?php
    # 判断一个变量是否为整数、小数、布尔值
    $str = '123456789';
    $is_rule = filter_var($str, FILTER_VALIDATE_INT);
    $is_rule = filter_var($str, FILTER_VALIDATE_FLOAT);
    $is_rule = filter_var($str, FILTER_VALIDATE_BOOLEAN);
    
    # 判断一个变量是否为IP地址、MAC地址、URL、邮箱
    $str = '123456789@qq.com';
    $is_rule = filter_var($str, FILTER_VALIDATE_IP);
    $is_rule = filter_var($str, FILTER_VALIDATE_MAC);
    $is_rule = filter_var($str, FILTER_VALIDATE_URL);
    $is_rule = filter_var($str, FILTER_VALIDATE_EMAIL);
    
    # 判断一个邮箱域名是否可用
    $domain = 'qq.com';
    $have_mx = checkdnsrr($domain, 'MX');
    
  15. php数组序列化、字符串反序列化

    <?php
    # 序列化
    $arr = ['a' => 1, 'b' => 2];
    $str = http_build_query($arr);
    echo $str;
    
    # 反序列化
    $str = 'a=1&b=2';
    parse_str($str, $arr);
    print_r($arr);
    
  16. php输出自定义长度的一段随机汉字

    <?php
    $length = 3;
    $unicode = "";
    for ($i = 1; $i <= $length; $i++) {
        $number = rand(0x4e00, 0x9fa5);
        $number = dechex($number);
        $unicode .= "\\u{$number}";
    }
    $chinese = json_decode("[\"{$unicode}\"]", true);
    $chinese = $chinese[0];
    echo $chinese;
    
  17. php超快的敏感词屏蔽功能

    <?php
    $str = 'ajbkcldmenf';
    //敏感词先分3类
    $bds1 = '/a|b|j/';
    $bds2 = '/c|d|k/';
    $bds3 = '/e|f|l/';
    $str = preg_replace($bds1,'*',$str);
    $str = preg_replace($bds2,'#',$str);
    $str = preg_replace($bds3,'?',$str);
    echo $str;
    
  18. php判断字符串是否为url

    <?php
    /**
     * 英文域名url正则
     *
     * 传输协议(字母开头紧接'://')
     * ^[a-z]+:\/\/
     *
     * 多级子域(字母、数字开头可以包含字母、数字、'_'、'-'且以'.'结尾的多组这种组合)
     * ([a-z0-9]{1}[a-z0-9_-]*\.)*
     *
     * 顶级域名(由.分割的1到多组字母、数字组合)
     * ([a-z0-9]+\.)*[a-z0-9]+
     *
     * 链接路由(以'/'开头的一段字符串)
     * (\/[^\f\n\r\t\v]*)*$
     *
     * 最终表达式
     * ^[a-z]+:\/\/([a-z0-9]{1}[a-z0-9_-]*\.)*([a-z0-9]+\.)*[a-z0-9]+(\/[^\f\n\r\t\v]*)*$
     */
    $regular = '/^[a-z]+:\/\/([a-z0-9]{1}[a-z0-9_-]*\.)*([a-z0-9]+\.)*[a-z0-9]+(\/[^\f\n\r\t\v]*)*$/';
    preg_match($regular, $url, $match);
    if (isset($match[0]) && $url == $match[0]) {
        return true;
    } else {
        return false;
    }
    
  19. php正则中文

    <?php
    //$regular = "/[\x{4e00}-\x{9fa5}]+/u"; //通过Unicode编码
    //$regular = "/[一-龥]+/"; //通过汉字(传入字符串编码必须与程序文件编码一致才有效)
    //举例如下:
    //章节名格式必须为: 第x章 xxx(其中x为数字,xxx为汉字)
    $chapter_name = '第123章 天黑了';
    $regular = "/^\x{7b2c}\d+\x{7ae0}\s[\x{4e00}-\x{9fa5}]+$/u";
    preg_match_all($regular, $chapter_name, $metch);
    if(isset($metch[0][0]) && $metch[0][0] == $chapter_name){
       echo "章节名格式正确";
    } else {
       echo "章节名格式错误";
    }
    
  20. php数字转中文

    <?php
    function small_number_to_chinese(int $num = 0)
    {
        if (empty($num)) {
        return "零";
       }
        if ($num > 9999) {
           return "数字过大,无法解析。";
        }
        $encode = 'UTF-8';
        $arr1 = array(
            '0' => '零',
            '1' => '一',
            '2' => '二',
            '3' => '三',
            '4' => '四',
            '5' => '五',
            '6' => '六',
            '7' => '七',
            '8' => '八',
            '9' => '九'
        );
        $arr2 = array(
            '1' => "",
            '2' => "十",
            '3' => "百",
            '4' => "千"
        );
        $len = strlen($num);
        $res = '';
        for ($i = 1; $i <= $len; $i++) {
            $str = substr($num, -$i, 1);
            $zh = $arr1[$str];
            $res = $zh . $arr2[$i] . $res;
        }
        $res = str_replace("零千", "零", $res);
        $res = str_replace("零百", "零", $res);
        $res = str_replace("零十", "零", $res);
        $res = str_replace("零零", "零", $res);
        $res = str_replace("零零", "零", $res);
        if (mb_substr($res, -1, 1, $encode) == "零") {
           $res = mb_substr($res, 0, -1, $encode);
        }
        return $res;
    }
    function number_to_chinese(int $num = 0)
    {
        if (empty($num)) {
           return "零";
        }
        $len = strlen($num);
        if ($len > 12) {
           return "该数字过大,无法解析。";
        }
        $arr = array(
            '4' => '',
            '8' => '万',
            '12' => '亿'
        );
        $res = '';
        for ($i = 4; $i <= $len; $i += 4) {
            $str = substr($num, -$i, 4);
            $str = (int)$str;
            $zh = small_number_to_chinese($str);
            $add = '';
            $hex = $arr[$i];
            if($str < 1000 && $str != 0){
               $add = "零";
            }
            if($str == 0){
                $zh = '';
                $hex = '';
            }
            $res = $add . $zh . $hex . $res;
        }
        if ($i - 4 < $len) {
            $len = $len - ($i - 4);
            $str = substr($num, 0, $len);
            $zh = small_number_to_chinese($str);
            $res = $zh . $arr[$i] . $res;
        }
        return $res;
    }
    //测试
    $a = 9;
    if($a <= 9999){
    echo small_number_to_chinese($a);
    }else{
    echo number_to_chinese($a);
    }
    
  21. php中文转数字

    <?php
    function strKToNum($str)
    {
        //只能处理千以内整数
        if (strstr($str, "万")) {
            return 0;
        }
        if($str == '零'){
            return 0;
        }
        $str = str_replace("一", "1", $str);
        $str = str_replace("二", "2", $str);
        $str = str_replace("三", "3", $str);
        $str = str_replace("四", "4", $str);
        $str = str_replace("五", "5", $str);
        $str = str_replace("六", "6", $str);
        $str = str_replace("七", "7", $str);
        $str = str_replace("八", "8", $str);
        $str = str_replace("九", "9", $str);
    
        $str = preg_replace("/千$/", "000", $str);
    
        $str = preg_replace("/千零1十$/", "010", $str);
        $str = preg_replace("/千零2十$/", "020", $str);
        $str = preg_replace("/千零3十$/", "030", $str);
        $str = preg_replace("/千零4十$/", "040", $str);
        $str = preg_replace("/千零5十$/", "050", $str);
        $str = preg_replace("/千零6十$/", "060", $str);
        $str = preg_replace("/千零7十$/", "070", $str);
        $str = preg_replace("/千零8十$/", "080", $str);
        $str = preg_replace("/千零9十$/", "090", $str);
    
        $str = str_replace("千零1十", "01", $str);
        $str = str_replace("千零2十", "02", $str);
        $str = str_replace("千零3十", "03", $str);
        $str = str_replace("千零4十", "04", $str);
        $str = str_replace("千零5十", "05", $str);
        $str = str_replace("千零6十", "06", $str);
        $str = str_replace("千零7十", "07", $str);
        $str = str_replace("千零8十", "08", $str);
        $str = str_replace("千零9十", "09", $str);
    
        $str = str_replace("千零1", "001", $str);
        $str = str_replace("千零2", "002", $str);
        $str = str_replace("千零3", "003", $str);
        $str = str_replace("千零4", "004", $str);
        $str = str_replace("千零5", "005", $str);
        $str = str_replace("千零6", "006", $str);
        $str = str_replace("千零7", "007", $str);
        $str = str_replace("千零8", "008", $str);
        $str = str_replace("千零9", "009", $str);
    
        $str = str_replace("千", "", $str);
    
        $str = preg_replace("/百$/", "00", $str);
    
        $str = str_replace("百零", "0", $str);
    
        $str = str_replace("百", "", $str);
    
        $str = preg_replace("/1十$/", "10", $str);
        $str = preg_replace("/2十$/", "20", $str);
        $str = preg_replace("/3十$/", "30", $str);
        $str = preg_replace("/4十$/", "40", $str);
        $str = preg_replace("/5十$/", "50", $str);
        $str = preg_replace("/6十$/", "60", $str);
        $str = preg_replace("/7十$/", "70", $str);
        $str = preg_replace("/8十$/", "80", $str);
        $str = preg_replace("/9十$/", "90", $str);
    
        $str = str_replace("1十", "1", $str);
        $str = str_replace("2十", "2", $str);
        $str = str_replace("3十", "3", $str);
        $str = str_replace("4十", "4", $str);
        $str = str_replace("5十", "5", $str);
        $str = str_replace("6十", "6", $str);
        $str = str_replace("7十", "7", $str);
        $str = str_replace("8十", "8", $str);
        $str = str_replace("9十", "9", $str);
    
        $str = preg_replace("/十$/", "10", $str);
    
        $str = str_replace("十", "1", $str);
    
        $str = str_replace("零", "", $str);
        return $str;
    }
    function strAToNum($str)
    {
        //只能处理千亿以内整数
        if (strstr($str, "万亿")) {
            return 0;
        }
        $arr = explode("万", $str);
        if (count($arr) == 1) {
            $num = strKToNum($arr[0]);
            return $num;
        } else {
            $num = strKToNum($arr[1]);
            $arr = explode("亿", $arr[0]);
            if (count($arr) == 1) {
                $num = strKToNum($arr[0]) . substr("000" . $num, -4);
                return $num;
            } else {
                $num = strKToNum($arr[0]) . substr("000" . strKToNum($arr[1]), -4) . substr("000" . $num, -4);
                return $num;
            }
        }
    }
    echo strAToNum('零') . PHP_EOL;
    echo strAToNum('十') . PHP_EOL;
    echo strAToNum('十二') . PHP_EOL;
    echo strAToNum('一十二') . PHP_EOL;
    echo strAToNum('八') . PHP_EOL;
    echo strAToNum('八十') . PHP_EOL;
    echo strAToNum('八十八') . PHP_EOL;
    echo strAToNum('八百') . PHP_EOL;
    echo strAToNum('八百零八') . PHP_EOL;
    echo strAToNum('八百八十') . PHP_EOL;
    echo strAToNum('八百八十八') . PHP_EOL;
    echo strAToNum('八千零八') . PHP_EOL;
    echo strAToNum('八千零八十') . PHP_EOL;
    echo strAToNum('八千零八十八') . PHP_EOL;
    echo strAToNum('八千八百') . PHP_EOL;
    echo strAToNum('八千八百零八') . PHP_EOL;
    echo strAToNum('八千八百八十') . PHP_EOL;
    echo strAToNum('八千八百八十八') . PHP_EOL;
    echo strAToNum('八千亿八千八百万零八十八') . PHP_EOL;
    
  22. php章节名格式化

    <?php
    $chapter_order = 24;
    $chapter_name = '第二十四章 一个好人';
    //去除格式为‘[三万三千三百三十三或33333][章|节|话|回|卷|null][非汉字、英文字母、数字、括号字符]’的章节前缀
    $regular1 = "/^[一二三四五六七八九十百千万0-9]+[章节话回卷]?[^\x{4e00}-\x{9fa5}a-zA-Z0-9()()]+/u";
    $chapter_name = preg_replace($regular1, '', $chapter_name);
    //去除【汉字、英文字母、数字、括号】以外的字符
    $regular2 = "/[^\x{4e00}-\x{9fa5}a-zA-Z0-9()()]+/u";
    $chapter_name = preg_replace($regular2, '', $chapter_name);
    //去除‘第xxx章’
    $regular3 = "/第(.*?)(章|节|话|回|卷)/";
    $chapter_name = preg_replace($regular3, '', $chapter_name);
    //添加‘第[数字序号]章’
    $chapter_name = "第{$chapter_order}章 {$chapter_name}";
    echo $chapter_name;
    
  23. 书籍文本按章处理为数组

    <?php
    $start = 0;
    $regular = '/第\d+章(.*?)\r\n|第[零一二三四五六七八九十百千万亿]+章(.*?)\r\n/';
    //test.txt为小说文本
    $str = file_get_contents(__DIR__ . '/test.txt');
    $str = str_replace('—','--',$str);
    $str = preg_replace('/[^\r\n\S]+/', "", $str);
    $str = preg_replace('/[\r\n]+/', "\r\n", $str);
    //获取章节名列表
    preg_match_all($regular, $str, $chanter_names, PREG_PATTERN_ORDER, 0);
    $chanter_names = $chanter_names[0];
    //获取章节内容列表
    $chanter_contents = preg_split($regular, $str, null);
    array_shift($chanter_contents);
    //判断处理后的格式是否合适
    //处理后的格式不合适则不处理
    $total_names = count($chanter_names);
    $total_contents = count($chanter_contents);
    if ($total_names != $total_contents) {
       die("章节文件格式有误{$total_names}_{$total_contents}");
    }
    //处理后的格式合适则处理
    $chapters = [];
    foreach ($chanter_names as $key => &$chanter_name) {
        $chapter_order = $key + $start + 1;
        $chanter_name = str_replace("\r\n", "", $chanter_name);
        $chanter_name = preg_replace('/第\d+章|第[零一二三四五六七八九十百千万亿]+章/', "第{$chapter_order}章 ", $chanter_name);
        $chapters[] = [
            'chapter_order' => $key + 1,
            'chapter_name' => $chanter_name,
            'chapter_content' => mb_substr($chanter_contents[$key], 0, 10)
        ];
    }
    print_r($chapters);
    

results matching ""

    No results matching ""