检查输入字符串是否匹配给定格式 laravel

check input string has match given format laravel

字符串的格式(x、y、z 是每次都会变化的变量)

ID:x Levely-z

An example for the string will be ID:1 Level3-Super user

x = 1

y = 3

z = Super user

有什么方法可以不递归地使用explode()来检查输入的字符串是否为这种格式?

//check if missing 'ID' word on heading then return error
if(count(explode(" ",$string)) == 2){
    //check id
    if(count(explode(":",(explode(" ",$string)[0]))) == 2){
        id=explode(":",(explode(" ",$string)[0]))[1];
        //check the rest
        if(count(explode("-",explode(" ",$string)[1]))==2){
            $name=explode("-",$string)[1];
            //remove strings 'Level' to get the level number
            $level=mb_substr(explode("-",explode(" ",$string)[1])[0],2,2,"UTF-8");
         } else {
             array_push($error_msg,'Wrong format!');
         }
     } else {
         array_push($error_msg,'Wrong format!');
     }
} else {
    array_push($error_msg,'Wrong format!');
}

如何为此使用 preg_match?所有变量的长度都是未知的

您可以使用 preg_match 检查字符串的格式。例如,以下正则表达式:

ID:[0-9] Level[0-9]-.*

应该匹配

ID:1 Level3-Super User

这是一种方法,使用命名组:

$str = "ID:1 Level3-Super user";
if (preg_match('/^ID:(?<X>\d+)\h+Level(?<Y>\d+)-(?<Z>.+)$/', $str, $m)) {
    foreach (['X','Y','Z'] as $ind) {echo "$ind: ",$m[$ind],"\n";}
} else {
    echo 'no matches';
}

输出:

X: 1
Y: 3
Z: Super user

正则表达式解释:

/               # regex delimiter
  ^             # beginning of line
    ID:         # literally 
    (?<X>\d+)   # named group X, 1 or more digits
    \h+         # 1 or more horizontal spaces
    Level       # literally
    (?<Y>\d+)   # named goup Y, 1 or ore digits
    -           # an hyphen
    (?<Z>.+)    # named group Z, 1 or more any character but newline
  $             # end of line
/               # regex delimiter