Skip to content

Commit

Permalink
text::limit_words(), text::limit_chars(), text::soft_limit_chars()
Browse files Browse the repository at this point in the history
UTF-8 compatible
  • Loading branch information
Geert authored and Geert committed Aug 28, 2007
1 parent 48f4ebf commit 0c73f2b
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 3 deletions.
6 changes: 3 additions & 3 deletions system/helpers/file.php
Expand Up @@ -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)
Expand Down Expand Up @@ -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
82 changes: 82 additions & 0 deletions system/helpers/text.php
@@ -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.