2010-10-29 154 views
0

在下面的功能,我想不過匹配的關鍵字不區分大小寫(應符合「藍色瑜伽墊」和「藍色瑜伽墊」)...不區分大小寫preg_replace_callback

,但目前只有與關鍵字匹配是同樣的情況。

$ mykeyword =「Blue Yoga Mats」;

$post->post_content = preg_replace_callback("/\b($mykeyword)\b/","doReplace", $post->post_content); 

// the callback function 
function doReplace($matches) 
{ 
    static $count = 0; 

    // switch on $count and later increment $count. 
    switch($count++) { 
     case 0: return '<b>'.$matches[1].'</b>'; // 1st instance, wrap in bold 
     case 1: return '<em>'.$matches[1].'</em>'; // 2nd instance, wrap in italics 
     case 2: return '<u>'.$matches[1].'</u>'; // 3rd instance, wrap in underline 
     default: return $matches[1];    // don't change others. 
      } 
    } 

回答

3

只需將i改性劑添加到您的正則表達式,使其執行不區分大小寫的匹配:

"/\b($mykeyword)\b/i" 

順便說一句,如果你還沒有,你需要逃避特殊字符的正則表達式您的關鍵字。如果有的話,他們可能會搞砸你的正則表達式,並導致PHP的警告/錯誤。呼叫preg_quote()您進行更換前:

$mykeyword_escaped = preg_quote($mykeyword, '/'); 
$post->post_content = preg_replace_callback("/\b($mykeyword_escaped)\b/i","doReplace", $post->post_content); 
+1

+1約'preg_quote'位(我把它添加到評論,但看到你在這裏,沒有必要對評論).. 。 – ircmaxell 2010-10-29 16:49:33

+0

感謝您的快速響應!任何想法如何保持匹配關鍵字已匹配和包裝的功能?例如,每次保存內容時,都會在每個關鍵字周圍包裝另一組標籤。如果我將關鍵字更改爲「關鍵字」,它可以工作,但是當關鍵字是內容塊的第一個字符時會錯過。 – 2010-10-29 16:58:54

+0

我剛剛修復了我的代碼。錯過了第二個代碼塊中的修飾符,傻了我。 – BoltClock 2010-10-29 17:00:54

0

添加了 「我」 修改到你的正則表達式:

/\b($mykeyword)\b/i 
0
$post->post_content = preg_replace_callback("/\b($mykeyword)\b/i","doReplace", $post->post_content); 

使用TOKENregexpTOKENi執行不區分大小寫的搜索。

請參閱PHP手冊中的Pattern Modifiers瞭解修飾符的全部細節。

0

使用/ I修改:

$post->post_content = preg_replace_callback("/\b($mykeyword)\b/i","doReplace", $post->post_content);