2011-07-07 98 views
3
preg_match('/te**ed/i', 'tested', $matches); 

給了我以下錯誤:的preg_match匹配模式

ERROR: nothing to repeat at offset 3

我該怎麼辦,讓圖案實際上包含*

+0

您是否試圖將「測試」與該正則表達式匹配? – alex

+0

我的意思是使用文字「te ** ed」。所以我假設逃避它是要解決問題:) – sniper

回答

7

要使用文字星號,您必須用反斜槓將它們轉義。要匹配字面te**ed你會使用這樣的表達式:

preg_match('/te\*\*ed/i', 'tested', $matches); // no match (te**ed != tested) 

但我懷疑這是你想要的。如果你的意思是,比賽任何字符,你需要使用.

preg_match('/te..ed/is', 'tested', $matches); // match 

如果你真的想任何兩個小寫字母,那麼這個表達式:

preg_match('/te[a-z]{2}ed/i', 'tested', $matches); // match 
+0

我的意思是使用文字「te ** ed」。所以我假設逃避它會解決問題:) – sniper

+0

@sniper:足夠公平,但承認表達式中的'$ matches'仍然是空的,而'preg_match('/ te \ * \ * ed/i' ,'te ** ed',$ matches)'會產生一個非空的結果。 –

+0

啊......這正是我需要的! :)是否有無論如何快速逃脫「te ** ed」在PHP?任何內置函數? – sniper

1

在任何字符之前加一個反斜線,告訴PHP該字符應該是原樣,而不是一個特殊的正則表達式字符。所以:

preg_match('/te\\**ed/i', 'tested', $matches); 
0

如果你想使用星號樣的搜索,你可以用下面的函數:

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

例子:

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