2014-08-28 38 views
0

我需要匹配兩個模式的字符串,兩個模式都必須匹配字符串。你可以把它想象成某種驗證鏈。PHP中的pattern1和pattern2的正則表達式驗證匹配

下面的代碼中的模式只是例子。

<?php 
$pattern1 = "^hello hi$"; 
$pattern2 = "^h?llo hi$"; 

// form pattern that checks that both patterns match 
$pattern3 = "/".??."/"; 

if(preg_match($pattern3,$string)) 
{ 
    //solved it 
} 
?> 

我知道下面的代碼是一個可能的解決方案,但我想知道能不能通過連接模式一起某種方式與一個做的preg_match。

<?php 
$pattern1 = "/^hello hi$/"; 
$pattern2 = "/^h?llo hi$/"; 


if(preg_match($pattern1,$string) && preg_match($pattern2,$string)) 
{ 
    //solved it 
} 
?> 

回答

2

在返回值之前,您可以使用積極的向前看來確保字符串匹配您想要的所有模式。喜歡的東西:

/^(?=PATH_1$)(?=PATH_N$).*/ 

因此,對於你的例子這將是

/^(?=hello hi$)(?=h.llo hi$).*/ 

DEMO

+0

結束了使用'/( ?=^hello hi $)(?=^h.llo hi $)。* /' – user1740331 2014-08-28 09:55:38

+0

@ user1740331完全一樣(至少在這種情況下) – Enissay 2014-08-28 15:27:15

0

不知道這是你想要什麼,但:

$pattern1 = "/^hello hi$/"; 
$pattern2 = "/^h?llo hi$/"; 
$pattern3 = "/^h[e?]llo hi$/"; 

if(preg_match($pattern3,$string)) 
{ 
    echo 'Y'; 
}else{ 
    echo 'N'; 
}