Permalink
Browse files

text::limit_words(), text::limit_chars(), text::soft_limit_chars()

UTF-8 compatible
  • Loading branch information...
1 parent 48f4ebf commit 0c73f2b91c11ed64fb4bda978541e8a8f85f6558 Geert committed Aug 28, 2007
Showing with 85 additions and 3 deletions.
  1. +3 −3 system/helpers/file.php
  2. +82 −0 system/helpers/text.php
View
@@ -44,7 +44,7 @@ public static function split($filename, $output_dir = FALSE, $piece_size = 10)
fclose($input_file);
// Returns the number of pieces that were created
- return ($piece-1);
+ return ($piece - 1);
}
public static function join($filename, $output = FALSE)
@@ -78,7 +78,7 @@ public static function join($filename, $output = FALSE)
fclose($output_file);
// Return the number of pieces joined
- return ($piece-1);
+ return ($piece - 1);
}
-} // End file Class
+} // End file class
View
@@ -0,0 +1,82 @@
+<?php defined('SYSPATH') or die('No direct access allowed.');
+
+class text {
+
+ /**
+ * Word limiter
+ *
+ * @access public
+ * @param string
+ * @param integer
+ * @param string
+ * @return string
+ */
+ public static function limit_words($str, $limit = 100, $end_char = '&#8230;')
+ {
+ $limit = (int) $limit;
+
+ if (trim($str) == '')
+ return $str;
+
+ if ($limit <= 0)
+ return $end_char;
+
+ preg_match('/^\s*(?:\S+\s*){1,'.$limit.'}/u', $str, $matches);
+
+ if (strlen($matches[0]) == strlen($str))
+ {
+ $end_char = '';
+ }
+
+ return rtrim($matches[0]).$end_char;
+ }
+
+ /**
+ * Character limiter
+ *
+ * @access public
+ * @param string
+ * @param integer
+ * @param string
+ * @return string
+ */
+ public static function limit_chars($str, $limit = 100, $end_char = '&#8230;')
+ {
+ $limit = (int) $limit;
+
+ if (trim($str) == '' OR utf8::strlen($str) <= $limit)
+ return $str;
+
+ return rtrim(utf8::substr($str, 0, $limit)).$end_char;
+ }
+
+ /**
+ * Character limiter that preserves words
+ *
+ * @access public
+ * @param string
+ * @param integer
+ * @param string
+ * @return string
+ */
+ public static function soft_limit_chars($str, $limit = 100, $end_char = '&#8230;')
+ {
+ $limit = (int) $limit;
+
+ if (trim($str) == '' OR utf8::strlen($str) <= $limit)
+ return $str;
+
+ if ($limit <= 0)
+ return $end_char;
+
+ preg_match('/^.{'.($limit - 1).'}\S*/us', $str, $matches);
+
+ if (strlen($matches[0]) == strlen($str))
+ {
+ $end_char = '';
+ }
+
+ return rtrim($matches[0]).$end_char;
+ }
+
+} // End text class

0 comments on commit 0c73f2b

Please sign in to comment.