Jump to content

Shorten String Nightmare


liamloveslearning

Recommended Posts

Hi all, im trying to shorten this string which cnotains about 1000 characters, to say 250

<?php echo $row_Best_Sellers['experience_name']; ?>

 

Ive tried using the below to no avail, can anybody give me some advice?

 

<?PHP
$small = some_function($row_Best_Sellers['experience_description']);
echo $small;

function some_function($string){
     $string = substr($string,0,100);
     $string = substr($string,0,strrpos($string," "));
     return $string;
}
?>

Link to comment
https://forums.phpfreaks.com/topic/213557-shorten-string-nightmare/
Share on other sites

I've also tried to no avail. 

<?php
$text = 'something massivvveeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee';
function ShortenText($text) 
{
  
$chars = 25;        $text = $text." "; 
$text = substr($text,0,$chars);
$text = substr($text,0,strrpos($text,' '));
$text = $text."...";        return $text; 
}
?>

What do you get as output?

 

$string = substr($string,0,100);

$string = substr($string,0,strrpos($string," "));

 

Should give you an output of less then 100 characters (unless the last character is a space of course). The below should give you the desired output.

 

function some_function($string, $max_avg_length = 250) {
    return substr($string, 0, (isset($string[$max_avg_length]) ? strrpos($string, ' ', $max_avg_length) : 0));
}

Thanks for your response ignace,

 

I managed to get it working using

<?php
echo substr($row_Best_Sellers['experience_description'],0,80)."...";
?>

but now im cropping my paragraph in the middle fo words, is there a way to exclude this?

Thanks for your response ignace,

 

I managed to get it working using

<?php
echo substr($row_Best_Sellers['experience_description'],0,80)."...";
?>

but now im cropping my paragraph in the middle fo words, is there a way to exclude this?

 

echo isset($row_Best_Sellers['experience_description'][90]) // make sure there is something after the 80th character
    // cut the string off at the space preceding the 80th character
    ? substr($row_Best_Sellers['experience_description'], 0, strrpos($row_Best_Sellers['experience_description'], ' ', 80)) . '...'
    : $row_Best_Sellers['experience_description']; // otherwise just print it

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.