Posts Tagged ‘pad’
Cut string to given length or word count easy with _str_cut()
Another simple function of my library (extended at 09-09-2008).
Use it when You need to cut some text/string to given length in chars or specified word count and wish to add some suffix at the end like » read more or …
From:
$_str = “Here’s a sampling of features that might make you want to use WordPress.com. (Besides it being run by some swell folks!) We’re not fancy-pants marketers“
$_str = _str_cut( $_str, 30, “ » read more”);
To:
Here’s a sampling of features » read more
/**
* (C)2008 savride.wordpress.com
* @return String cut to needed length and with suffix if need one
* for example "..." as default or "<a href=" or what you just enter
* @param $_str Object given string
* @param $_len Object new length to set
* @param $_more Object[optional] suffix string instead of "..." fe. <a href="http://set_some.link.com">Link name set</a>
* @param $_cnt_words - cut to given words NUM - UPDATE
*/
function _str_cut( $_str, $_len, $_more = " ...", $_cnt_words = false, $_separator = " ")
{
$_str = strip_tags( $_str );
// return by WORD COUNT - update
if( $_cnt_words )
{
$_new_str = "";
if( $_cnt_words == 1)
return strtok( $_str, $_separator );
$_new_str .= $_separator.strtok( $_str, $_separator );
while( $_cnt_words > 0 )
{
$_new_str .= $_separator.strtok( $_separator );
$_cnt_words--;
}
return trim($_new_str, $_separator);
}
// return by WORD COUNT - update
$_start_len = strlen( $_str);
$_new_len = $_len - strlen( strip_tags($_more));
if ( $_start_len >= $_new_len)
{
$_str = substr( $_str, 0, $_new_len);
$_str = preg_replace( '/\s+[^\s]+?$/', "", $_str);
$_str .= " ".$_more;
}
return( $_str);
}
Feel free to use it.