Search code examples
phparrayslaravelpreg-matchstring-comparison

check input string has match given format laravel


Format of the string (x,y,z are the variables that will vary every time)

ID:x Levely-z

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

x = 1

y = 3

z = Super user

Is there any methods not to use explode() recursively to check whether the input string has this format?

//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!');
}

How do I use preg_match for this? All of the variables will have unknown length


Solution

  • You can use preg_match to check a string's format. For example, the following regex:

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

    Should match

    ID:1 Level3-Super User