limit text length in php and provide 'Read more' link - php

I have text stored in the php variable $text. This text can be 100 or 1000 or 10000 words. As currently implemented, my page extends based on the text, but if the text is too long the page looks ugly.
I want to get the length of the text and limit the number of characters to maybe 500, and if the text exceeds this limit I want to provide a link saying, "Read more." If the "Read More" link is clicked, it will show a pop with all the text in $text.

This is what I use:
// strip tags to avoid breaking any html
$string = strip_tags($string);
if (strlen($string) > 500) {
// truncate string
$stringCut = substr($string, 0, 500);
$endPoint = strrpos($stringCut, ' ');
//if the string doesn't contain any space then it will cut without word basis.
$string = $endPoint? substr($stringCut, 0, $endPoint) : substr($stringCut, 0);
$string .= '... Read More';
}
echo $string;
You can tweak it further but it gets the job done in production.

$num_words = 101;
$words = array();
$words = explode(" ", $original_string, $num_words);
$shown_string = "";
if(count($words) == 101){
$words[100] = " ... ";
}
$shown_string = implode(" ", $words);

There is an appropriate PHP function: substr_replace($text, $replacement, $start).
For your case, because you already know all the possibilities of the text length (100, 1000 or 10000 words), you can simply use that PHP function like this:
echo substr_replace($your_text, "...", 20);
PHP will automatically return a 20 character only text with ....
Se the documentation by clicking here.

I have combine two different answers:
Limit the characters
Complete HTML missing tags
$string = strip_tags($strHTML);
$yourText = $strHTML;
if (strlen($string) > 350) {
$stringCut = substr($post->body, 0, 350);
$doc = new DOMDocument();
$doc->loadHTML($stringCut);
$yourText = $doc->saveHTML();
}
$yourText."...<a href=''>View More</a>"

Simple use this to strip the text :
echo strlen($string) >= 500 ?
substr($string, 0, 490) . ' [Read more]' :
$string;
Edit and finally :
function split_words($string, $nb_caracs, $separator){
$string = strip_tags(html_entity_decode($string));
if( strlen($string) <= $nb_caracs ){
$final_string = $string;
} else {
$final_string = "";
$words = explode(" ", $string);
foreach( $words as $value ){
if( strlen($final_string . " " . $value) < $nb_caracs ){
if( !empty($final_string) ) $final_string .= " ";
$final_string .= $value;
} else {
break;
}
}
$final_string .= $separator;
}
return $final_string;
}
Here separator is the href link to read more ;)

<?php $string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.";
if (strlen($string) > 25) {
$trimstring = substr($string, 0, 25). ' readmore...';
} else {
$trimstring = $string;
}
echo $trimstring;
//Output : Lorem Ipsum is simply dum [readmore...][1]
?>

This method will not truncate a word in the middle.
list($output)=explode("\n",wordwrap(strip_tags($str),500),1);
echo $output. ' ... Read more';

Limit words in text:
function limitTextWords($content = false, $limit = false, $stripTags = false, $ellipsis = false)
{
if ($content && $limit) {
$content = ($stripTags ? strip_tags($content) : $content);
$content = explode(' ', $content, $limit+1);
array_pop($content);
if ($ellipsis) {
array_push($content, '...');
}
$content = implode(' ', $content);
}
return $content;
}
Limit chars in text:
function limitTextChars($content = false, $limit = false, $stripTags = false, $ellipsis = false)
{
if ($content && $limit) {
$content = ($stripTags ? strip_tags($content) : $content);
$ellipsis = ($ellipsis ? "..." : $ellipsis);
$content = mb_strimwidth($content, 0, $limit, $ellipsis);
}
return $content;
}
Use:
$text = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.";
echo limitTextWords($text, 5, true, true);
echo limitTextChars($text, 5, true, true);

Basically, you need to integrate a word limiter (e.g. something like this) and use something like shadowbox. Your read more link should link to a PHP script that displays the entire article. Just setup Shadowbox on those links and you're set. (See instructions on their site. Its easy.)

Another method: insert the following in your theme's function.php file.
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'custom_trim_excerpt');
function custom_trim_excerpt($text) { // Fakes an excerpt if needed
global $post;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$text = strip_tags($text);
$excerpt_length = x;
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words) > $excerpt_length) {
array_pop($words);
array_push($words, '...');
$text = implode(' ', $words);
}
}
return $text;
}
You can use this.

<?php
$images_path = 'uploads/adsimages/';
$ads = mysql_query("select * from tbl_postads ORDER BY ads_id DESC limit 0,5 ");
if(mysql_num_rows($ads)>0)
{
while($ad = mysql_fetch_array($ads))
{?>
<div style="float:left; width:100%; height:100px;">
<div style="float:left; width:40%; height:100px;">
<li><img src="<?php echo $images_path.$ad['ads_image']; ?>" width="100px" height="50px" alt="" /></li>
</div>
<div style="float:left; width:60%; height:100px;">
<li style="margin-bottom:4%;"><?php echo substr($ad['ads_msg'],0,50);?><br/> read more..</li>
</div>
</div>
<?php }}?>

I Guess this will help you fix your problem please check under given Function : trims text to a space then adds ellipses if desired
#param string $input text to trim
#param int $length in characters to trim to
#param bool $ellipses if ellipses (...) are to be added
#param bool $strip_html if html tags are to be stripped
#return string
function trim_text($input, $length, $ellipses = true, $strip_html = true) {
//strip tags, if desired
if ($strip_html) {
$input = strip_tags($input);
}//no need to trim, already shorter than trim length
if (strlen($input) <= $length) {
return $input;
}
//find last space within length
$last_space = strrpos(substr($input, 0, $length), ' ');
$trimmed_text = substr($input, 0, $last_space);
//add ellipses (...)
if ($ellipses) {
$trimmed_text .= '...';
}
return $trimmed_text;}

This worked for me.
// strip tags to avoid breaking any html
$string = strip_tags($string);
if (strlen($string) > 500) {
// truncate string
$stringCut = substr($string, 0, 500);
$endPoint = strrpos($stringCut, ' ');
//if the string doesn't contain any space then it will cut without word basis.
$string = $endPoint? substr($stringCut, 0, $endPoint) : substr($stringCut, 0);
$string .= '... Read More';
}
echo $string;
Thanks #webbiedave

Related

PHP: How can I cut the word and add "..."

How can I cut the words and add "..." after reaching 4 or 5 words?
The code below states I did the character-based word cuttingb but I need it now to be by word.
Currently I have this kind of code:
if(strlen($post->post_title) > 35 )
{
$titlep = substr($post->post_title, 0, 35).'...';
}
else
{
$titlep = $post->post_title;
}
and this is the output of title:
if ( $params['show_title'] === 'true' ) {
$title = '<h3 class="wp-posts-carousel-title">';
$title.= '' . $titlep . '';
$title.= '</h3>';
}
Typically, I'll explode the body and pull out the first x characters.
$split = explode(' ', $string);
$new = array_slice ( $split, 0 ,5);
$newstring = implode( ' ', $new) . '...';
Just know, this method is slow.
Variant #1
function crop_str_word($text, $max_words = 50, $sep = ' ')
{
$words = split($sep, $text);
if ( count($words) > $max_words )
{
$text = join($sep, array_slice($words, 0, $max_words));
$text .=' ...';
}
return $text;
}
Variant #2
function crop_str_word($text, $max_words, $append = ' …')
{
$max_words = $max_words+1;
$words = explode(' ', $text, $max_words);
array_pop($words);
$text = implode(' ', $words) . $append;
return $text;
}
Variant #3
function crop_str_word($text, $max_words)
{
$words = explode(' ',$text);
if(count($words) > $max_words && $max_words > 0)
{
$text = implode(' ',array_slice($words, 0, $max_words)).'...';
}
return $text;
}
via
You should use str_replace function of PHP.
str_replace('your word', '...', $variable);
read that article: http://php.net/manual/en/function.str-replace.php
In WordPress this functionality is done by wp_trim_words() function.
<?php
if(strlen($post->post_title) > 35 )
{
$titlep = wp_trim_words( $post->post_title, 35, '...' );
}
else
{
$titlep = $post->post_title;
}
?>
If you do this functionality using PHP then write code as below:
<?php
$titlep = strlen($post->post_title) > 35 ? substr($post->post_title, 0, 35).'...' : $post->post_title;
?>

How to insert word-wrap function to auto-break a long word in PHP?

How can I insert word-wrap function so that any word that is too long doesn't cut <div> border but line-returns itself?
The following is the variable I want to word-wrap
$body = nl2br(addslashes($_POST['body']));
try out these links:
Smarter word-wrap in PHP for long words?
http://php.net/manual/en/function.wordwrap.php
http://www.w3schools.com/php/func_string_wordwrap.asp
And a custom Function:
function smart_wordwrap($string, $width = 75, $break = "\n") {
// split on problem words over the line length
$pattern = sprintf('/([^ ]{%d,})/', $width);
$output = '';
$words = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
foreach ($words as $word) {
if (false !== strpos($word, ' ')) {
// normal behaviour, rebuild the string
$output .= $word;
} else {
// work out how many characters would be on the current line
$wrapped = explode($break, wordwrap($output, $width, $break));
$count = $width - (strlen(end($wrapped)) % $width);
// fill the current line and add a break
$output .= substr($word, 0, $count) . $break;
// wrap any remaining characters from the problem word
$output .= wordwrap(substr($word, $count), $width, $break, true);
}
}
// wrap the final output
return wordwrap($output, $width, $break);
}
$string = 'hello! toolongheretoolonghereooheeeeeeeeeeeeeereisaverylongword but these words are shorterrrrrrrrrrrrrrrrrrrr';
echo smart_wordwrap($string, 11) . "\n";

Php substr entire words

How can i substr 20 chars from $xbio and get only complete words?
$xbio = 'word1 ord2 word3 word4 and so on';
echo ''.substr($xbio, 0, 20).'...';
TY
Found this searching stackoverflow - tell me what do you think please:
<? $xbio = preg_replace('/\s+?(\S+)?$/', '', substr($xbio, 0, 50)); ?>
This is the function i always use:
# advanced substr
function gen_string($string,$min) {
$text = trim(strip_tags($string));
if(strlen($text)>$min) {
$blank = strpos($text,' ');
if($blank) {
# limit plus last word
$extra = strpos(substr($text,$min),' ');
$max = $min+$extra;
$r = substr($text,0,$max);
if(strlen($text)>=$max) $r=trim($r,'.').'...';
} else {
# if there are no spaces
$r = substr($text,0,$min).'...';
}
} else {
# if original length is lower than limit
$r = $text;
}
return $r;
}
preg_match('/^([a-zA-Z0-9 ]{1,20})\\b/', $xbio, $matches);
echo $matches[1];
This is a function that i use for this kind of task:
function truncate($str, $maxLength, $append = '...') {
if (strlen($str) > $maxLength) {
$str = substr($str, 0, $maxLength);
$str = preg_replace('/\s+.*?$/', '', $str); // this line is important for you
$str = trim($str);
$str .= $append:
}
return $str;
}

cut text after (x) amount of characters

This is in wordpress (not sure that makes a difference)
This bit of php outputs the post title
<?php echo $data['nameofpost']; ?>
It's simple text which can be anywhere up to 100 chars long. What i'd like is if the chars outputted are over 20 long to display '...' or simply nothing at all.
Thanks
After you check the string length with strlen use substr
$string = "This is a large text for demonstrations purposes";
if(strlen($string) > 20) $string = substr($string, 0, 20).'...';
echo $string;
Outputs
"This is a large text..."
Another way to cut the string off at the end of a word is with a regex. This one is set to cut off at 100 characters or the nearest word break after 100 characters:
function firstXChars($string, $chars = 100)
{
preg_match('/^.{0,' . $chars. '}(?:.*?)\b/iu', $string, $matches);
return $matches[0];
}
<?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 common improvement would be to try to cut the string 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 want to use the mb_ multibyte versions of the string ops to count characters more appropriately.
in your theme file use something like this
try using <div class="teaser-text"><?php the_content_limit(100, ''); ?></div>
then in the 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 :)
if(count($data['nameofpost']) > 20)
{
echo(substr($data['nameofpost'], 0, 17)."...");
}
For $data['nameofpost'] greater then 20 chars it will output the first 17 plus three dots ....

Making sure PHP substr finishes on a word not a character

I know how to use the substr function but this will happy end a string halfway through a word. I want the string to end at the end of a word how would I go about doing this? Would it involve regular expression? Any help very much appreciated.
This is what I have so far. Just the SubStr...
echo substr("$body",0,260);
Cheers
substr($body, 0, strpos($body, ' ', 260))
It could be done with a regex, something like this will get up to 260 characters from the start of string up to a word boundary:
$line=$body;
if (preg_match('/^.{1,260}\b/s', $body, $match))
{
$line=$match[0];
}
Alternatively, you could maybe use the wordwrap function to break your $body into lines, then just extract the first line.
You can try this:
$s = substr($string, 0, 261);
$result = substr($s, 0, strrpos($s, ' '));
You could do this: Find the first space from the 260th character on and use that as the crop mark:
$pos = strpos($body, ' ', 260);
if ($pos !== false) {
echo substr($body, 0, $pos);
}
wordwrap and explode then first array element is you want
$wr=wordwrap($text,20,':');
$strs=explode(":",$wr);
$strs[0]
I use this solution:
$maxlength = 50;
substr($name, 0, ($spos = strpos($name, ' ', $lcount = count($name) > $maxlength ? $lcount : $maxlength)) ? $spos : $lcount );
Or inline:
substr($name, 0, ($spos = strpos($name, ' ', $lcount = count($name) > 50 ? $lcount : 50)) ? $spos : $lcount );
function substr_word($body,$maxlength){
if (strlen($body)<$maxlength) return $body;
$body = substr($body, 0, $maxlength);
$rpos = strrpos($body,' ');
if ($rpos>0) $body = substr($body, 0, $rpos);
return $body;
}
What about this?
/**
* #param string $text
* #param int $limit
* #return string
*/
public function extractUncutPhrase($text, $limit)
{
$delimiters = [',',' '];
$marks = ['!','?','.'];
$phrase = substr($text, 0, $limit);
$nextSymbol = substr($text, $limit, 1);
// Equal to original
if ($phrase == $text) {
return $phrase;
}
// If ends with delimiter
if (in_array($nextSymbol, $delimiters)) {
return $phrase;
}
// If ends with mark
if (in_array($nextSymbol, $marks)) {
return $phrase.$nextSymbol;
}
$parts = explode(' ', $phrase);
array_pop($parts);
return implode(' ', $parts); // Additioanally you may add ' ...' here.
}
Tests:
public function testExtractUncutPhrase()
{
$stringUtils = new StringUtils();
$text = 'infant ton-gue could make of both names nothing';
$phrase = 'infant';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 11));
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 12));
$text = 'infant tongue5';
$phrase = 'infant';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 11));
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 7));
}
public function testExtractUncutPhraseEndsWithDelimiter()
{
$stringUtils = new StringUtils();
$text = 'infant tongue ';
$phrase = 'infant tongue';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
$text = 'infant tongue,';
$phrase = 'infant tongue';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
}
public function testExtractUncutPhraseIsSentence()
{
$stringUtils = new StringUtils();
$text = 'infant tongue!';
$phrase = 'infant tongue!';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 14));
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 100));
$text = 'infant tongue!';
$phrase = 'infant tongue!';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
$text = 'infant tongue.';
$phrase = 'infant tongue.';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
}
$pos = strpos($body, $wordfind);
echo substr($body,0, (($pos)?$pos:260));
public function Strip_text($data, $size, $lastString = ""){
$data = strip_tags($data);
if(mb_strlen($data, 'utf-8') > $size){
$result = mb_substr($data,0,mb_strpos($data,' ',$size,'utf-8'),'utf-8');
if(mb_strlen($result, 'utf-8') <= 0){
$result = mb_substr($data,0,$size,'utf-8');
$result = mb_substr($result, 0, mb_strrpos($result, ' ','utf-8'),'utf-8');;
}
if(strlen($lastString) > 0) {
$result .= $lastString;
}
}else{
$result = $data;
}
return $result;
}
Pass the string into funtion Strip_text("Long text with html tag or without html tag", 15)
Then this function will return the first 15 character from the html string without html tags. When string less than 15 character then return the full string other wise it will return the 15 character with $lastString parameter string.
Example:
Strip_text("<p>vijayDhanasekaran</p>", 5)
Result: vijay
Strip_text("<h1>vijayDhanasekaran<h1>",5,"***....")
Result: vijay***....
Try This Function..
<?php
/**
* trims text to a space then adds ellipses if desired
* #param string $input text to trim
* #param int $length in characters to trim to
* #param bool $ellipses if ellipses (...) are to be added
* #param bool $strip_html if html tags are to be stripped
* #param bool $strip_style if css style are to be stripped
* #return string
*/
function trim_text($input, $length, $ellipses = true, $strip_tag = true,$strip_style = true) {
//strip tags, if desired
if ($strip_tag) {
$input = strip_tags($input);
}
//strip tags, if desired
if ($strip_style) {
$input = preg_replace('/(<[^>]+) style=".*?"/i', '$1',$input);
}
if($length=='full')
{
$trimmed_text=$input;
}
else
{
//no need to trim, already shorter than trim length
if (strlen($input) <= $length) {
return $input;
}
//find last space within length
$last_space = strrpos(substr($input, 0, $length), ' ');
$trimmed_text = substr($input, 0, $last_space);
//add ellipses (...)
if ($ellipses) {
$trimmed_text .= '...';
}
}
return $trimmed_text;
}
?>

Categories