ONYX
ONYX

Reputation: 5859

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

}

Upvotes: 1

Views: 72

Answers (2)

Naumov
Naumov

Reputation: 1167

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.

Upvotes: 0

Asaph
Asaph

Reputation: 162841

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')).

Upvotes: 1

Related Questions