Str.php

<?php
/**
 * Created by PhpStorm.
 * User: mingzhanghui
 * Date: 10/9/2019
 * Time: 11:54
 * 自定义的字符串函数
 */

namespace app\crm\utils;

class Str {
    /**

     * @param $s string
     * @return int
    '["26","27"]' => 26  php系统函数intval 返回0
    '["26,27"]' => 26
    "26" => 26
     */
    public static function intval(/* string */ $s) {
        // 已经是数字类型 不处理
        if (is_int($s)) {
            return $s;
        }
        $digits = [];
        $t = 0; // 0 - other, 1 -digit

        for ($i = 0; isset($s[$i]); $i++) {
            $c = ord($s[$i]);
            if (48 <= $c && $c < 58) {
                if (empty($digits)) {
                    array_push($digits, $c - 48);
                } else {
                    if ($t == 1) {
                        array_push($digits, $c - 48);
                    }
                }
                $t = 1;
            } else {
                if (empty($digits)) {
                    $t = 0;
                } else {
                    break;
                }
            }
        }
        return array_reduce($digits, function($acc, $c) {
            return $acc * 10 + $c;
        }, 0);
    }

    /**
     * @param $s "工商银行-622848000000000"
     * @return string "622848000000000"
     */
    public static function extractNumbers($s) {
        $ns = "";
        for ($i = 0; isset($s[$i]); $i++) {
            $c = ord($s[$i]);
            if (48 <= $c && $c <58) {
                $ns .= $s[$i];
            }
        }
        return $ns;
    }

}