検索の修正
守矢諏訪子 <suwako@076.moe>、2026-11-10 15:53
コミット 526c49dcf713d6b2e35dd31a895cdfbd216e6c09
・親 8ebe52c
・ファイルを見る
1個のファイル、+16 -10
| @@ -308,20 +308,26 @@ | ||
| 308 | 308 | return $text; |
| 309 | 309 | } |
| 310 | 310 | |
| 311 | - $highlightedText = $text; | |
| 311 | + $alts = []; | |
| 312 | 312 | |
| 313 | 313 | foreach ($keywords as $keyword) { |
| 314 | 314 | $keyword = trim($keyword); |
| 315 | - if (empty($keyword)) continue; | |
| 316 | - | |
| 317 | - // キーワードを大文字小文字を区別せずに置換 | |
| 318 | - $highlightedText = preg_replace( | |
| 319 | - '/('.preg_quote($keyword, '/').')/iu', | |
| 320 | - '<span class="search-highlight">$1</span>', | |
| 321 | - $highlightedText | |
| 322 | - ); | |
| 315 | + $escaped = htmlspecialchars($keyword, ENT_QUOTES, 'UTF-8'); | |
| 316 | + if ($escaped === '') continue; | |
| 317 | + $alts[] = preg_quote($escaped, '/'); | |
| 323 | 318 | } |
| 319 | + if (empty($alts)) return $text; | |
| 320 | + $pattern = '/('.implode('|', $alts).')/iu'; | |
| 321 | + | |
| 322 | + $parts = preg_split('/(<[^>]*>|&[#\w]+;)/u', $text, -1, PREG_SPLIT_DELIM_CAPTURE); | |
| 323 | + if ($parts === false) return $text; | |
| 324 | + | |
| 325 | + foreach ($parts as $i => $part) { | |
| 326 | + if ($part === '' || $part[0] === '<' || $part[0] === '&') continue; | |
| 327 | + $res = preg_replace($pattern, '<span class="search-highlight">$1</span>', $part); | |
| 328 | + if ($res !== null) $parts[$i] = $res; | |
| 329 | + } | |
| 324 | 330 | |
| 325 | - return $highlightedText; | |
| 331 | + return implode('', $parts); | |
| 326 | 332 | } |
| 327 | 333 | } |