2011-04-11 67 views
3

我想通過星號將字符串與另一個字符串進行匹配。匹配帶星號的字符串

例子:我有

$var = "*world*"; 

我想打一個函數,要麼返回true或false,以配合我的字符串。 不區分大小寫

example: 
match_string("*world*","hello world") // returns true 
match_string("world*","hello world") // returns false 
match_string("*world","hello world") // returns true 
match_string("world*","hello world") // returns false 
match_string("*ello*w*","hello world") // returns true 
match_string("*w*o*r*l*d*","hello world") // returns true 

的*只會在範圍內匹配任何字符。我嘗試使用preg_match幾個小時沒有運氣。

+2

什麼是你最後一次嘗試? – 2011-04-11 13:35:16

+0

我最後一次嘗試是用*(*)替換*以使用preg_match,但不知道我犯了什麼錯誤。 – TDSii 2011-04-11 13:43:16

+0

你從哪裏得到字符串?爲什麼不使用「正常」正則表達式? – 2011-04-11 13:43:33

回答

3
function match_string($pattern, $str) 
{ 
    $pattern = preg_replace('/([^*])/e', 'preg_quote("$1", "/")', $pattern); 
    $pattern = str_replace('*', '.*', $pattern); 
    return (bool) preg_match('/^' . $pattern . '$/i', $str); 
} 

而且上面運行它在你的測試用例:

bool(true) 
bool(false) 
bool(true) 
bool(false) 
bool(true) 
bool(true) 
+0

'preg_quote()'應該總是包含第二個參數,分隔符。在這種情況下,它應該是「/」。如果你不包含它,match_string(「hello/*」,「hello world」)會拋出一個錯誤。 – mcrumley 2011-04-11 13:54:28

1

試試這樣說:

function match_string($match, $string) { 
    return preg_match("/$match/i", $string); 
} 

注意的preg_match實際上返回匹配的數目,但它比較真/假作品(0 =假,> 0 = TRUE)。請注意模式末尾的i標誌使匹配不區分大小寫。

這會爲你的下面的示例工作:

example: 
match_string("world","hello world") // returns true 
match_string(" world","hello world") // returns true 
match_string("world ","hello world") // returns false 
match_string("ello w","hello world") // returns true 
match_string("world","hello world") // returns true 
1
function match_string($patt, $haystack) { 
    $regex = '|^'. str_replace('\*', '.*', preg_quote($patt)) .'$|is'; 
    return preg_match($regex, $haystack); 
} 
+0

或使用'preg_quote':http://php.net/manual/en/function.preg-quote.php – 2011-04-11 13:44:59

+0

感謝您的建議,我已經包括它。 – Czechnology 2011-04-11 13:48:09

0

您可以使用下面的代碼來生成適當的正則表達式。否更換回調,沒有自行車碼

$var = "*world*"; 
$regex = preg_quote($var, '/'); // escape initial string 
$regex = str_replace(preg_quote('*'), '.*?', $regex); // replace escaped asterisk to .*? 
$regex = "/^$regex$/i"; // you have case insensitive regexp 
0

沒有必要preg_matchstr_replace這裏。 PHP有一個通配符比較功能,專門針對這種情況提出:

fnmatch()

你的測試工作像預期與​​:

fnmatch("*world*","hello world") // returns true 
fnmatch("world*","hello world") // returns false 
fnmatch("*world","hello world") // returns true 
fnmatch("world*","hello world") // returns false 
fnmatch("*ello*w*","hello world") // returns true 
fnmatch("*w*o*r*l*d*","hello world") // returns true 
+0

請注意,'fnmatch'使用適合當前操作系統shell的通配符,這可能不是您想要的。這意味着如果沒有關於它將運行的操作系統的一些假設,代碼是不可移植的。 – Jason 2016-04-04 22:38:33