| 1: | <?php
|
| 2: | |
| 3: | |
| 4: | |
| 5: | |
| 6: | |
| 7: | |
| 8: | |
| 9: | |
| 10: |
|
| 11: |
|
| 12: | namespace Xmf;
|
| 13: |
|
| 14: | |
| 15: | |
| 16: | |
| 17: | |
| 18: | |
| 19: | |
| 20: | |
| 21: | |
| 22: | |
| 23: |
|
| 24: | class Highlighter
|
| 25: | {
|
| 26: | |
| 27: | |
| 28: |
|
| 29: | const ENCODING = 'UTF-8';
|
| 30: |
|
| 31: | |
| 32: | |
| 33: | |
| 34: | |
| 35: | |
| 36: | |
| 37: | |
| 38: | |
| 39: | |
| 40: | |
| 41: | |
| 42: | |
| 43: |
|
| 44: | public static function apply($words, $body, $pre = '<mark>', $post = '</mark>')
|
| 45: | {
|
| 46: | if (!is_array($words)) {
|
| 47: | $words = preg_replace('/[\s]+/', ' ', $words);
|
| 48: | $words = explode(' ', $words);
|
| 49: | }
|
| 50: | foreach ($words as $word) {
|
| 51: | $body = static::splitOnTag($word, $body, $pre, $post);
|
| 52: | }
|
| 53: |
|
| 54: | return $body;
|
| 55: | }
|
| 56: |
|
| 57: | |
| 58: | |
| 59: | |
| 60: | |
| 61: | |
| 62: | |
| 63: | |
| 64: | |
| 65: | |
| 66: |
|
| 67: | protected static function splitOnTag($needle, $haystack, $pre, $post)
|
| 68: | {
|
| 69: | $encoding = static::ENCODING;
|
| 70: | return preg_replace_callback(
|
| 71: | '#((?:(?!<[/a-z]).)*)([^>]*>|$)#si',
|
| 72: | function ($capture) use ($needle, $pre, $post, $encoding) {
|
| 73: | $haystack = $capture[1];
|
| 74: | if (function_exists('mb_substr')) {
|
| 75: | $p1 = mb_stripos($haystack, $needle, 0, $encoding);
|
| 76: | $l1 = mb_strlen($needle, $encoding);
|
| 77: | $ret = '';
|
| 78: | while ($p1 !== false) {
|
| 79: | $ret .= mb_substr($haystack, 0, $p1, $encoding) . $pre
|
| 80: | . mb_substr($haystack, $p1, $l1, $encoding) . $post;
|
| 81: | $haystack = mb_substr($haystack, $p1 + $l1, mb_strlen($haystack), $encoding);
|
| 82: | $p1 = mb_stripos($haystack, $needle, 0, $encoding);
|
| 83: | }
|
| 84: | } else {
|
| 85: | $p1 = stripos($haystack, $needle);
|
| 86: | $l1 = strlen($needle);
|
| 87: | $ret = '';
|
| 88: | while ($p1 !== false) {
|
| 89: | $ret .= substr($haystack, 0, $p1) . $pre . substr($haystack, $p1, $l1) . $post;
|
| 90: | $haystack = substr($haystack, $p1 + $l1);
|
| 91: | $p1 = stripos($haystack, $needle);
|
| 92: | }
|
| 93: | }
|
| 94: | $ret .= $haystack . $capture[2];
|
| 95: |
|
| 96: | return $ret;
|
| 97: | },
|
| 98: | $haystack
|
| 99: | );
|
| 100: | }
|
| 101: | }
|
| 102: | |