Search code examples
phpregexlaravelassert

Laravel - Assertion multiple regex


I have two regex :

'/^(?:0(?:21|9[0-9]))?[0-9]{8}$/'

And

'/(0|\\+98 | 98)?([ ]|,|-|[()]){0,2}9[1|2|3|4]([ ]|,|-|[()]){0,2}(?:[0-9]([ ]|,|-|[()]){0,2}){8}/'

I want to use Assertion::regex method in Laravel. Here is that method:

Assertion.php:

public static function regex($value, $pattern, $message = null, $propertyPath = null)
{
    static::string($value, $message, $propertyPath);

    if (! preg_match($pattern, $value)) {
        $message = sprintf(
            $message ?: 'Value "%s" does not match expression.',
            static::stringify($value)
        );

        throw static::createException($value, $message, static::INVALID_REGEX, $propertyPath, array('pattern' => $pattern));
    }

    return true;
}

How to use and check multiple regex in Assertion::regex($phone, $regex); ?

I used to initialize $regex with :

$regex = '/^(?:0(?:21|9[0-9]))?[0-9]{8}$/ | /(0|\\+98 | 98)?([ ]|,|-|[()]){0,2}9[1|2|3|4]([ ]|,|-|[()]){0,2}(?:[0-9]([ ]|,|-|[()]){0,2}){8}/'

Actually , I gave an error :

preg_match(): Unknown modifier '|'

Any suggestion?


Solution

  • If you want to use an alternation between two regexes the pipe must be within the regex:

    ^(?:0(?:21|9[0-9]))?[0-9]{8}$|(0|\\+98 | 98)?([ ]|,|-|[()]){0,2}9[1|2|3|4]([ ]|,|-|[()]){0,2}(?:[0-9]([ ]|,|-|[()]){0,2}){8}
                                 ^
    

    The string concatenation you did lead php to understand that your regex finished after this backslash:

    /^(?:0(?:21|9[0-9]))?[0-9]{8}$/
                                  ^
    

    Trying to interpret what followed as modifiers, thus the error message you've got.