PageRenderTime 40ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/dooframework/helper/DooTextHelper.php

http://doophp.googlecode.com/
PHP | 319 lines | 177 code | 37 blank | 105 comment | 22 complexity | e9490e4c8b0568ce8654d71429aa41b8 MD5 | raw file
  1. <?php
  2. /**
  3. * DooTextHelper class file.
  4. *
  5. * @author Leng Sheng Hong <darkredz@gmail.com>
  6. * @link http://www.doophp.com/
  7. * @copyright Copyright &copy; 2009 Leng Sheng Hong
  8. * @license http://www.doophp.com/license
  9. */
  10. /**
  11. * A helper class that helps to manipulate text.
  12. *
  13. * @author Leng Sheng Hong <darkredz@gmail.com>
  14. * @version $Id: DooTextHelper.php 1000 2009-08-4 11:17:22
  15. * @package doo.helper
  16. * @since 1.1
  17. */
  18. class DooTextHelper {
  19. /**
  20. * Generates a random string.
  21. * @param int $length Length of the generated string
  22. * @return string
  23. */
  24. public static function randomName( $length = 6 ){
  25. $allchar = 'abcdefghijklmnopqrstuvwxyz01234567890';
  26. $str = "" ;
  27. mt_srand (( double) microtime() * 1000000 );
  28. for( $i=0; $i<$length; $i++ )
  29. $str .= substr( $allchar, mt_rand (0,36), 1 ) ;
  30. return date("YmdHis").rand(1000,9999).$str ;
  31. }
  32. /**
  33. * Removing repeated words from text.
  34. * @param string $str Original text to be processed.
  35. * @return string
  36. */
  37. public static function removeRepeatWords($str){
  38. return preg_replace("/s(w+s)1/i", "$1", $str);
  39. }
  40. /**
  41. * Convert all URLs in the text into hyperlinks.
  42. *
  43. * All URLs are converted. http://domain.com, www.domain.com, email@address.com
  44. * Passed in a false to disable converting Email to link.
  45. *
  46. * @param string $str
  47. * @param string $classname CSS class name of the link tag
  48. * @param string $target Target: _self, _blank, _parent, etc.
  49. * @param bool $convertEmail Convert email address into links. Default true.
  50. * @param string $emailHide Change this if you want to hide the email. eg. leng[AT]doophp.com, value = '[AT]'
  51. * @return string
  52. */
  53. public static function convertUrl($str, $classname='', $target='', $convertEmail=true, $emailHide='@'){
  54. if($classname!='')
  55. $classname = "class=\"$classname\"";
  56. if($target!='')
  57. $target = "target=\"$target\"";
  58. $str = preg_replace("#([ ]|^|])([a-z]+?)://([a-z0-9@:\-]+)\.([a-z0-9@:\-.\~]+)((?:/[^ ]*)?[^][\".,?!;: ])#i", "\\1<a href=\"\\2://\\3.\\4\\5\" $target $classname>\\2://\\3.\\4\\5</a>", $str);
  59. $str = preg_replace("#([ ]|^|])www\.([a-z0-9\-]+)\.([a-z0-9:\-.\~]+)((?:/[^ ]*)?[^][\".,?!;: ])#i", "\\1<a href=\"http://www.\\2.\\3\\4\" $target $classname>www.\\2.\\3\\4</a>", $str);
  60. if($convertEmail)
  61. if($emailHide=='@')
  62. $str = preg_replace("#([ ]|^|])([a-z0-9\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)?[\w]+[^][\".,?!;: ])#i", "\\1<a href=\"mailto:\\2@\\3\" $target $classname>\\2@\\3</a>", $str);
  63. else
  64. $str = preg_replace("#([ ]|^|])([a-z0-9\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)?[\w]+[^][\".,?!;: ])#i", "\\1\\2$emailHide\\3", $str);
  65. return $str;
  66. }
  67. /**
  68. * Count words.
  69. * @param string $str Input String
  70. * @return int Number of words
  71. */
  72. public static function countWord($str){
  73. return str_word_count($str);
  74. }
  75. /**
  76. * Escape/encode a string
  77. *
  78. * @param string $str The input string
  79. * @param string $escapeType Escape type: html, htmlall, url
  80. * @param string $charSet Character set, default ISO-8859-1
  81. * @return string
  82. */
  83. public static function escape($str, $escapeType='html', $charSet='ISO-8859-1'){
  84. switch ($escapeType){
  85. case 'url':
  86. return rawurlencode($str);
  87. case 'urlpathinfo':
  88. return str_replace('%2F','/',rawurlencode($str));
  89. case 'quotes':
  90. return preg_replace("%(?<!\\\\)'%", "\\'", $str);
  91. case 'hex':
  92. $rs = '';
  93. for($i=0; $i < strlen($str); $i++) {
  94. $rs .= '%' . bin2hex($str[$i]);
  95. }
  96. return $rs;
  97. case 'hexentity':
  98. $rs = '';
  99. for($i=0; $i < strlen($str); $i++) {
  100. $rs .= '&#x' . bin2hex($str[$i]) . ';';
  101. }
  102. return $rs;
  103. case 'decentity':
  104. $rs = '';
  105. for($i=0; $i < strlen($str); $i++) {
  106. $rs .= '&#' . ord($str[$i]) . ';';
  107. }
  108. return $rs;
  109. case 'html':
  110. return htmlspecialchars($str, ENT_COMPAT, $charSet);
  111. case 'htmlall':
  112. return htmlentities($str, ENT_COMPAT, $charSet);
  113. case 'js':
  114. return strtr($str, array('\\'=>'\\\\',"'"=>"\\'",'"'=>'\\"',"\r"=>'\\r',"\n"=>'\\n','</'=>'<\/'));
  115. case 'mail':
  116. return str_replace(array('@', '.'),array(' [AT] ', ' [DOT] '), $str);
  117. case 'nonstd':
  118. $rs = '';
  119. for($i = 0, $length = strlen($str); $i < $length; $i++) {
  120. $ord = ord(substr($str, $i, 1));
  121. $rs .= $ord >= 126 ? '&#' . $ord . ';' : substr($str, $i, 1);
  122. }
  123. return $rs;
  124. default:
  125. return $str;
  126. }
  127. }
  128. /**
  129. * Filter/censor word(s) from a string input
  130. *
  131. * <p>A list of disallowed words will be replaced to '*' or the replacement value
  132. * from the input string.</p>
  133. *
  134. * @param string $str Input string to be processed
  135. * @param array $censorWords List of words to be censored
  136. * @param string $replacement Optional replacement string for the censored word
  137. * @param bool $word True to be an exact word, False to censor within word 'Youprofanity'
  138. * @return string
  139. */
  140. public static function filter($str, $censorWords, $replacement='*', $word=true){
  141. if(!$word)
  142. return str_ireplace($censorWords, $replacement, $str);
  143. foreach($censorWords as $c)
  144. $str = preg_replace("/\b(" . str_replace('\*', '\w*?', preg_quote($c)) . ")\b/i", $replacement, $str);
  145. return $str;
  146. }
  147. /**
  148. * Highlight PHP code
  149. *
  150. * @param string $str String of the PHP script
  151. * @return string
  152. */
  153. public static function highlightPHP($str){
  154. $str = str_replace(array('&lt;', '&gt;'), array('<', '>'), $str);
  155. $str = str_replace(array('&lt;?php', '?&gt;', '\\'), array('phptagopen', 'phptagclose', 'backslashtmp'), $str);
  156. $str = '<?php //tempstart' . "\n" . $str . '//tempend ?>';
  157. $str = highlight_string($str, true);
  158. if(abs(phpversion()) < 5){
  159. $str = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $str);
  160. $str = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $str);
  161. }
  162. $str = preg_replace("#\<code\>.+?//tempstart\<br />\</span\>#is", "<code>\n", $str);
  163. //$str = preg_replace("#\<code\>.+?//tempstart\<br />#is", "<code>\n", $str);
  164. $str = preg_replace("#//tempend.+#is", "</span>\n</code>", $str);
  165. $str = str_replace(array('phptagopen', 'phptagclose', 'backslashtmp'), array('&lt;?php', '?&gt;', '\\'), $str);
  166. return $str;
  167. }
  168. /**
  169. * Highlight word(s) within a string
  170. *
  171. * @param string $str String input
  172. * @param string $phrase The phrase to be highlighted
  173. * @param string $tagOpen HTML tag added right before the word
  174. * @param string $tagClose HTML tag added right after the word
  175. * @return string
  176. */
  177. public static function highlightWord($str, $phrase, $tagOpen='<span style="font-weight:bold;background-color:#ffff00">', $tagClose='</span>'){
  178. return preg_replace('/(' . preg_quote($phrase) . ')/i', $tagOpen . "\\1" . $tagClose, $str);
  179. }
  180. /**
  181. * Limit the string to a certain amount of words.
  182. *
  183. * @param string $str String input
  184. * @param int $limit Number of words to limit
  185. * @param string $ending End characters. Default '...'
  186. * @return string
  187. */
  188. public static function limitWord($str, $limit, $ending='...'){
  189. if(strlen($str) < $limit)
  190. return $str;
  191. $words = explode(' ', preg_replace("/\s+/", ' ', preg_replace("/(\r\n|\r|\n)/", " ", $str)));
  192. if(sizeof($words)<=$limit)
  193. return $str;
  194. $str = '';
  195. for($i=0; $i<$limit; $i++){
  196. $str .= $words[$i].' ';
  197. }
  198. return $str . $ending;
  199. }
  200. /**
  201. * Limit the string to a certain amount of characters.
  202. *
  203. * @param string $str String input
  204. * @param int $limit Number of characters to limit
  205. * @param string $ending End characters. Default '...'
  206. * @param string $encoding The character encoding. eg. utf8
  207. * @return string
  208. */
  209. public static function limitChar($str, $limit, $ending='...', $encoding=null){
  210. if($encoding==null){
  211. if(strlen($str) <= $limit)
  212. return $str;
  213. return substr($str, 0, $limit) . $ending;
  214. }else{
  215. if(mb_strlen($str, $encoding) <= $limit)
  216. return $str;
  217. return mb_substr($str, 0, $limit, $encoding) . $ending;
  218. }
  219. }
  220. /**
  221. * Replace all repeated spaces, newlines and tabs.
  222. *
  223. * @param string $str String input
  224. * @param string $replace Replacement value (optional)
  225. * @return string
  226. */
  227. public static function strip($str, $replace=' '){
  228. return preg_replace('/\s+/', $replace, $str);
  229. }
  230. /**
  231. * Word wraping of string
  232. *
  233. * Anything within [nowrap][/nowrap] in the string won't be wrapped.
  234. *
  235. * @param string $str String input
  236. * @param int $charLimit Character limit per line
  237. * @param string $breakline Break line HTML replacement
  238. * @return string
  239. */
  240. public static function wordwrap($str, $charLimit, $breakline='<br/>'){
  241. if(!is_numeric($charLimit))
  242. $charLimit = 76;
  243. $str = preg_replace("| +|", " ", $str);
  244. $str = preg_replace("/\r\n|\r/", "\n", $str);
  245. $nowrap = array();
  246. if(preg_match_all("|(\[nowrap\].+?\[/nowrap\])|s", $str, $matches)){
  247. $count = count($matches['0']);
  248. for($i = 0; $i < $count; $i++){
  249. $nowrap[] = $matches['1'][$i];
  250. $str = str_replace($matches['1'][$i], "[[nowrapped".$i."]]", $str);
  251. }
  252. }
  253. $str = wordwrap($str, $charLimit, $breakline, false);
  254. $output = '';
  255. foreach(explode($breakline, $str) as $line) {
  256. if(strlen($line) <= $charLimit){
  257. $output .= $line . $breakline;
  258. continue;
  259. }
  260. $temp = '';
  261. while((strlen($line)) > $charLimit){
  262. if(preg_match("!\[url.+\]|://|wwww.!", $line))
  263. break;
  264. $temp .= substr($line, 0, $charLimit-1);
  265. $line = substr($line, $charLimit-1);
  266. }
  267. $output .= ($temp != '' ? $temp.$line : $line) . $breakline;
  268. }
  269. if(count($nowrap) > 0){
  270. foreach($nowrap as $key => $val){
  271. $output = str_replace("[[nowrapped".$key."]]", $val, $output);
  272. }
  273. }
  274. $output = str_replace(array('[nowrap]', '[/nowrap]'), '', $output);
  275. return $output;
  276. }
  277. }