| src/Pluf/Text.php |
| 28 | 28 | class Pluf_Text |
| 29 | 29 | { |
| 30 | 30 | /** |
| 31 | * Wrap a string containing HTML code. |
| 32 | * |
| 33 | * The HTML is not broken, words are broken only if very long. |
| 34 | * |
| 35 | * Improved from a version available on php.net |
| 36 | * |
| 37 | * @see http://www.php.net/manual/en/function.wordwrap.php#89782 |
| 38 | * |
| 39 | * @param string The string to wrap |
| 40 | * @param int The maximal length of a string (45) |
| 41 | * @param string Wrap string ("\n") |
| 42 | * @return string Wrapped string |
| 43 | */ |
| 44 | public static function wrapHtml($string, $length=45, $wrapString="\n") |
| 45 | { |
| 46 | $wrapped = ''; |
| 47 | $word = ''; |
| 48 | $html = false; |
| 49 | $line_len = 0; |
| 50 | $n = mb_strlen($string); |
| 51 | for ($i=0; $i<$n; $i++) { |
| 52 | $char = mb_substr($string, $i, 1); |
| 53 | /** HTML Begins */ |
| 54 | if ($char === '<') { |
| 55 | if(!empty($word)) { |
| 56 | $wrapped .= $word; |
| 57 | $word = ''; |
| 58 | } |
| 59 | $html = true; |
| 60 | $wrapped .= $char; |
| 61 | } elseif ($char === '>') { |
| 62 | /** HTML ends */ |
| 63 | $html = false; |
| 64 | $wrapped .= $char; |
| 65 | } elseif ($html) { |
| 66 | /** If this is inside HTML -> append to the wrapped string */ |
| 67 | $wrapped .= $char; |
| 68 | } elseif ($char === "\n") { |
| 69 | /** Whitespace characted / new line */ |
| 70 | $wrapped .= $word.$char; |
| 71 | $word = ''; |
| 72 | $line_len = 0; |
| 73 | } elseif ($char === ' ' || $char === "\t") { |
| 74 | $word .= $char; |
| 75 | if(strlen($word) + $line_len <= $length) { |
| 76 | $line_len += strlen($word); |
| 77 | $wrapped .= $word; |
| 78 | $word = ''; |
| 79 | } |
| 80 | |
| 81 | } else { |
| 82 | /** Check chars */ |
| 83 | $word .= $char; |
| 84 | if (mb_strlen($word) >= $length) { |
| 85 | $wrapped .= $word.$wrapString; |
| 86 | $word = ''; |
| 87 | $line_len = 0; |
| 88 | } elseif (mb_strlen($word) + $line_len > $length) { |
| 89 | $wrapped .= $wrapString; |
| 90 | $line_len = 0; |
| 91 | } |
| 92 | } |
| 93 | } |
| 94 | if ($word !== '') { |
| 95 | $wrapped .= $word; |
| 96 | } |
| 97 | return $wrapped; |
| 98 | } |
| 99 | |
| 100 | /** |
| 31 | 101 | * Given a string, cleaned from the not interesting characters, |
| 32 | 102 | * returns an array with the words as index and the number of |
| 33 | 103 | * times it was in the text as the value. |