简体   繁体   中英

php build or replace part of regular expression

I have this regular expression and I want to replace the "lb" part with the parameter that's being passed in with what ever weight they want to use so what I have is this

protected function validateCheckWeight($attribute, $value, $parameters) 
{        
    // this always outputs correctly either true or false
    return preg_match('/^(?!0\d|0lb$)\d+(?:\.\d+)?lb$/', $value);
}

and what I want is this but it doesn't work when doing validation

protected function validateCheckWeight($attribute, $value, $parameters) 
{        

    return return preg_match('@/^(?!0\d|0' . $parameters[0] .'$)\d+(?:\.\d+)?' . $parameters[0] . '$/@', $value);    
}



protected function validateCheckWeight($attribute, $value, $parameters) 
{   
    dd('@/^(?!0\d|0' . $parameters[0] .'$)\d+(?:\.\d+)?' . $parameters[0] . '$/@');
    // output "@/^(?!0\d|0kg$)\d+(?:\.\d+)?kg$/@"
    return preg_match('@/^(?!0\d|0' . $parameters[0] .'$)\d+(?:\.\d+)?' . $parameters[0] . '$/@', $value);
    // this always outputs false

}

You have 2 different delimiters in your regex, @ and / . I've just confirmed that if you remove @ from the beginning and end of your regular expression, your function returns true for the inputs mentioned in your comments ( $value = "kg" , $parameters = array('kg') ).

If I correct understand this question you can

return strlen(parameters[0]) == strlen(rtrim(parameters[0],'lb'));

but I think again don't correct understand this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM