I have made a news script, but I now want to modify it so that it puts like 75 words insted of 500 characters followed by ..., I just think it looks crap.

I have created the code that should explode all the words by spaces ' ', and them stick that into a for loop that will count to 75 and stick them onto a variable including spaces.

$preview = explode(' ', $news['post']);
 $i = 0;
 $news['preview'] = '';
 for($i = 0; $i > 250; $i++) {
   $news['preview'] .= $preview[$i];
   if($i != 249) $news['preview'] .= ' ';
 }

for some reason when I output $news nothing comes out and I don't know why.

There are to two things I want to know.

1. Why is this simple script not working?
2. Is there a better way of doing this?

1. Why is this simple script not working?

For starters, if you want it to loop, switch the > to < in your loop. You're terminating the condition right off the bat, so it's not looping.

2. Is there a better way of doing this?

I use this function. Here's the function with an example:

<?
// Get the first $wordcount words from a sentence - used for long descriptions.
function get_words($str, $wordcount) {
$words=preg_split('/([\s.,;]+)/',$str,$wordcount+1,PREG_SPLIT_DELIM_CAPTURE);
array_pop($words);
return(implode('',$words)); 
} 
 
$data = "this is a piece of text yeah baby yeah!";
$newdata = get_words($data, 4);
echo $newdata;
?>

lol woops, thanx a lot for your help. It always useful to have someone else look at your code.

I have however modified the function so that if it has less than the designated words it will not do the array_pop

Cool. Glad it's working for ya.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.