文字参照の&を取り去った文字列(copy、tradeなど)を検索した場合に、文字参照文字の&が&のまま出力されてしまう。
tradeを検索して、ページ出力した場合の例
JAVA&<strong class="word0">trade;</strong>
文字参照に含まれる文字列を検索した場合の処理にちょっと工夫が要りそうです。…というか、直前に&がある場合の処理というべきかな。
diff -u -r1.77 html.php --- html.php 26 May 2003 13:57:04 -0000 1.77 +++ html.php 27 May 2003 09:42:40 -0000 @@ -83,9 +83,10 @@ { $s_key = htmlspecialchars($key); $search_word .= " <strong class=\"word$id\">$s_key</strong>"; - $to = "<strong class=\"word$id\">\$1</strong>"; - $body = preg_replace("/(?:^|(?<=>))([^<]*)/e", - 'preg_replace("/($pattern)/",$to,\'$1\')',$body); + $body = preg_replace_callback( + "/(<[^>]*>|&(?:#[0-9]+|#x[0-9a-f]+|[0-9a-zA-Z]+);)|($pattern)/", + create_function('$arr', + 'return $arr[1] ? $arr[1] : "<strong class=\"word'.$id.'\">{$arr[2]}</strong>";'),$body); $id++; } $body = "<div class=\"small\">$_msg_word$search_word</div>$hr\n$body";
diff -u -r1.77 html.php --- html.php 26 May 2003 13:57:04 -0000 1.77 +++ html.php 27 May 2003 10:59:09 -0000 @@ -83,9 +83,12 @@ { $s_key = htmlspecialchars($key); $search_word .= " <strong class=\"word$id\">$s_key</strong>"; - $to = "<strong class=\"word$id\">\$1</strong>"; - $body = preg_replace("/(?:^|(?<=>))([^<]*)/e", - 'preg_replace("/($pattern)/",$to,\'$1\')',$body); + $pattern = ($s_key{0} == '&') ? + "/(<[^>]*>)|($pattern)/" : + "/(<[^>]*>|&(?:#[0-9]+|#x[0-9a-f]+|[0-9a-zA-Z]+);)|($pattern)/"; + $body = preg_replace_callback($pattern, + create_function('$arr', + 'return $arr[1] ? $arr[1] : "<strong class=\"word'.$id.'\">{$arr[2]}</strong>";'),$body); $id++; } $body = "<div class=\"small\">$_msg_word$search_word</div>$hr\n$body";