2010-08-26 59 views
0

我寫了一個正則表達式,但它並不像我期望的那樣工作。看看請瞭解以下正則表達式


preg_match_all("/([\.\:]?)(.{0,65}?[^\s]*".preg_quote($word)."[^\s]*.{0,65})/siu",$content,$matched); 

[^\s]*".preg_quote($word)."[^\s] //

這部分匹配整個單詞,如果它包含的關鍵字,例如,如果我搜索WOR關鍵字匹配關鍵字

.{0,65}?[^\s]*".preg_quote($word)."[^\s]*.{0,65}

在這裏,我起身到65個字符之前和關鍵字,即後。我會得到

多的話這裏關鍵字這裏換句話說


而現在,是什麼問題。我嘗試匹配從開始的句子,如果{65}個字符中有任何[。:]字符

如果我有sach結構 - word1 word2 {小於65字符這裏} {關鍵詞這裏的其他字符}

我的預期,如果我寫([\.\:]?)(.{0,65}?[^\s]*".preg_quote($word)."[^\s]*.{0,65})

它將匹配.{less then 65 character here} keyword {65 characters}

但事實並非如此。部分[\.\:]?對正則表達式沒有任何影響。它匹配所有{65}個字符。

我需要從begining匹配句子,如果內65個字符的句子開始關鍵字之前

回答

1

[.:]?的意思是「匹配點(.),冒號(:),或什麼也沒有」;如果下一個字符不是點或冒號,則([.:]?)不匹配。然後.{0,65}匹配高達65的任何東西,包括.:。我認爲這是你在找什麼:

$source='A regular expression (regex or regexp for short) is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids.'; 
$word = 'regular'; 
preg_match_all('#[^.:]{0,65}\b'.preg_quote($word).'\b.{0,65}#siu', $source, $matches); 
print_r($matches); 

輸出:

Array 
(
    [0] => Array 
    (
     [0] => A regular expression (regex or regexp for short) is a special text string 
     [1] => You can think of regular expressions as wildcards on steroids. 
    ) 

) 

(見直播上Ideone

+0

完美。謝啦:/ – Simon 2010-08-26 09:42:15

1

只需更換拳頭

.{0,65} 

通過

[^\.\:]{0,65} 

畢竟,它可能看起來像

preg_match_all("/([^\.\:]{0,65}?[^\s]*".preg_quote($word)."[^\s]*.{0,65})/siu",$content,$matched);