2010-11-04 79 views
0

在下面的替換腳本中,如果$ myKeyword是「test」,並且替換文本是「This,test can be a test」,我希望被替換的文本是「This,< b> test」可以是< em> test </em>「爲什麼preg_replace跳過替換文本的第一個實例?

但是,我得到的是:這個測試可以是< b> test </b>。

我想確定爲什麼它跳過關鍵字「測試」的第一個實例。

function save_rseo_content($content){ 
    global $post; 
    $mykeyword = rseo_getKeyword($post); 
    $mykeyword = " ".preg_quote($mykeyword, '/'); 

    /*had to add " " before keyword so that the it skips the instance 
     where the keyword has already been formatted. Only matches " keyword"*/ 

    $theContent = 
    preg_replace_callback("/\b($mykeyword)\b/i","doReplace", $content); 
return $theContent; 
} 

function doReplace($matches) 
{ 
    static $count = 0; 
    switch($count++) { 
    case 0: return ' <b>'.trim($matches[1]).'</b>'; 
    case 1: return ' <em>'.trim($matches[1]).'</em>'; 
    case 2: return ' <u>'.trim($matches[1]).'</u>'; 
    default: return $matches[1]; 
     } 
} 
+0

@Scott:它工作正常的me..please再次檢查。 – codaddict 2010-11-04 19:16:02

+1

有可能你沒有告訴我們......;)因爲它在這裏工作得很好。 – netcoder 2010-11-04 19:20:55

+0

然後必須是WordPress預解析器的東西。我會更上游。我認爲它是WP如何取代逗號的問題。如果我刪除逗號,它工作正常。 – 2010-11-04 19:23:12

回答

0

而不是檢測關鍵字之前有空格,它很可能是更好的使用負回顧後爲>字符:

preg_replace_callback("/\b(?<!>)($mykeyword)\b/i","doReplace", $content); 
相關問題