Cut text after (x) number of characters
5 answers
Another way to cut a line at the end of a word is with a regular expression. This option is disabled with 100 characters or the closest word break after 100 characters:
function firstXChars($string, $chars = 100)
{
preg_match('/^.{0,' . $chars. '}(?:.*?)\b/iu', $string, $matches);
return $matches[0];
}
+4
a source to share
<?php
function abbreviate($text, $max) {
if (strlen($text)<=$max)
return $text;
return substr($text, 0, $max-3).'...';
}
?>
<?php echo htmlspecialchars(abbreviate($data['nameofpost'], 20)); ?>
A general improvement would be to try and strip the line at the end of a word:
if (strlen($text)<=$max)
return $text;
$ix= strrpos($text, ' ', $max-2);
if ($ix===FALSE)
$text= substr($text, 0, $max-3);
else
$text= substr($text, 0, $ix);
return $text.'...';
If you are using UTF-8 strings, you would like to use the mb_
multibyte version of the ops string to count more characters accordingly.
0
a source to share
in your theme file use something like this try using <div class="teaser-text"><?php the_content_limit(100, ''); ?></div>
then in functions.php files use this
function the_content_limit($max_char, $more_link_text = '(more...)', $stripteaser = 0, $more_file = '')
{
$content = get_the_content($more_link_text, $stripteaser, $more_file);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
$content = strip_tags($content);
if (strlen($_GET['p']) > 0)
{
echo "<div>";
echo $content;
echo "</div>";
}
else if ((strlen($content)>$max_char) && ($espacio = strpos($content, " ", $max_char )))
{
$content = substr($content, 0, $espacio);
$content = $content;
echo "<div>";
echo $content;
echo "...";
echo "</div>";
}
else {
echo "<div>";
echo $content;
echo "</div>";
}
}
good luck :)
0
a source to share