示例#1
0
 public static function highlight($text, $match, &$n = null)
 {
     $n = 0;
     if ($match === null || $match === false || $match === "" || $text == "") {
         return htmlspecialchars($text);
     }
     $mtext = $text;
     $offsetmap = null;
     $flags = "";
     if (is_object($match)) {
         if (!isset($match->preg_raw)) {
             $match = $match->preg_utf8;
             $flags = "u";
         } else {
             if (preg_match('/[\\x80-\\xFF]/', $text)) {
                 list($mtext, $offsetmap) = UnicodeHelper::deaccent_offsets($mtext);
                 $match = $match->preg_utf8;
                 $flags = "u";
             } else {
                 $match = $match->preg_raw;
             }
         }
     }
     $s = $clean_initial_nonletter = false;
     if ($match !== null && $match !== "") {
         if (str_starts_with($match, self::UTF8_INITIAL_NONLETTER)) {
             $clean_initial_nonletter = true;
         }
         if ($match[0] !== "{") {
             $match = "{(" . $match . ")}is" . $flags;
         }
         $s = preg_split($match, $mtext, -1, PREG_SPLIT_DELIM_CAPTURE);
     }
     if (!$s || count($s) == 1) {
         return htmlspecialchars($text);
     }
     $n = (int) (count($s) / 2);
     if ($offsetmap) {
         for ($i = $b = $o = 0; $i < count($s); ++$i) {
             if ($s[$i] !== "") {
                 $o += strlen($s[$i]);
                 $e = UnicodeHelper::deaccent_translate_offset($offsetmap, $o);
                 $s[$i] = substr($text, $b, $e - $b);
                 $b = $e;
             }
         }
     }
     if ($clean_initial_nonletter) {
         for ($i = 1; $i < count($s); $i += 2) {
             if ($s[$i] !== "" && preg_match('{\\A((?!\\pL|\\pN)\\X)(.*)\\z}us', $s[$i], $m)) {
                 $s[$i - 1] .= $m[1];
                 $s[$i] = $m[2];
             }
         }
     }
     for ($i = 0; $i < count($s); ++$i) {
         if ($i % 2 && $s[$i] !== "") {
             $s[$i] = '<span class="match">' . htmlspecialchars($s[$i]) . "</span>";
         } else {
             $s[$i] = htmlspecialchars($s[$i]);
         }
     }
     return join("", $s);
 }