2017-01-09 44 views
0

我有兩個正則表達式:Laravel - 斷言多個正則表達式

'/^(?: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}/' 

我想用斷言::正則表達式方法Laravel。下面是一個方法:

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; 
} 

如何使用和斷言::正則表達式檢查多個正則表達式($電話,$正則表達式);

我用來初始化$正則表達式有:

$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}/' 

其實,我給了一個錯誤:

的preg_match():未知的修飾詞 '|'

有什麼建議嗎?

+0

你的第一個正則表達式是錨定的,第二個不是。它的目的是?如果是,您可以使用['(?:^(?: 0(?:21 | 9 [0-9]))?[0-9] {8} $ |(0 | \ +98 | 98)? [ - ,()] {0,2} 9 [1-4] [ - ,()] {0,2}(?:[0-9] [ - ,()] {0,2}){8 })'](https://regex101.com/r/1ssxXA/3)。如果不是,請嘗試['^(?:(?: 0(?:21 | 9 [0-9]))?[0-9] {8} |(0 | \ +98 | 98)?[ - , ():{0,2} 9 [1-4] [ - ,()] {0,2}(?:[0-9] [ - ,()] {0,2}){8})$ '](https://regex101.com/r/1ssxXA/2)。 –

回答

1

如果你想使用兩個正則表達式之間的交替管道必須在正則表達式中:

^(?: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} 
          ^

字符串連接你確實導致PHP來了解您的正則表達式這反斜線後完成:

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

試圖解釋後面的修飾符,從而得到錯誤信息。

+0

謝謝你的回答。 – AFN