Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
text::limit_words(), text::limit_chars(), text::soft_limit_chars()
UTF-8 compatible
- Loading branch information
Geert
authored and
Geert
committed
Aug 28, 2007
1 parent
48f4ebf
commit 0c73f2b
Showing
2 changed files
with
85 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 = '…') | ||
{ | ||
$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 = '…') | ||
{ | ||
$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 = '…') | ||
{ | ||
$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 |