2011-12-21 126 views
0

我有一段代碼突出顯示一個短語。它適用於短語不含可變符號($)的單詞,數字和符號(如(',*,$,))。以下是我的代碼。那麼我應該怎麼做才能突出顯示完整的短語?

if (!empty($_GET['gid'])) { 
    function highlightWords($string, $words) 
    { 
     $string = str_ireplace($words, '<span class="highlight_word">'.$words.'</span>', $string); 
     /*** return the highlighted string ***/ 
     return $string; 
    } 

    /*** example usage ***/ 
    $string = file_get_contents('referencefiles/Microsoft.txt', FILE_USE_INCLUDE_PATH); 
    $words = 'Paper August 2003'; 

    /*** highlight the words ***/ 
    $string = highlightWords($string, $words); 
    echo $string; 
} 
?> 

回答

1

模式字符串中的任何元字符都需要轉義。 請檢查http://www.php.net/manual/en/ref.regex.php

+0

對不起。我只是PHP的初學者。你能舉個例子嗎?是這樣的$ words = preg_match('/^[A-Z_ - ] * $ /','Paper August 2003'); ? – user1072986 2011-12-21 09:55:52

+0

使用反斜槓來轉義正則表達式元字符,如* $ example:preg_match('\ *',$ string); – mustafa 2011-12-21 11:13:30

0

這能否幫助:

 
function highlight_matches($find_text, $text) { 
    return preg_replace("/($find_text)/i", '$1', $text); 
} 
echo highlight_matches($string, $words); 
+0

不,它沒有幫助 – user1072986 2011-12-21 10:04:39

相關問題