Getting words
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.
[php]$preview = explode(' ', $news['post']);
$i = 0;
$news['preview'] = '';
for($i = 0; $i > 250; $i++) {
$news['preview'] .= $preview[$i];
if($i != 249) $news['preview'] .= ' ';
}[/php]
for some reason when I output $news['preview'] 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?
Ragnarok
Junior Poster in Training
94 posts since Mar 2004
Reputation Points: 10
Solved Threads: 0
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:
[php]
<?
// 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;
?>
[/php]
samaru
a.k.a inscissor
1,256 posts since Feb 2002
Reputation Points: 262
Solved Threads: 18
lol woops, thanx a lot for your help. It always useful to have someone else look at your code.
Ragnarok
Junior Poster in Training
94 posts since Mar 2004
Reputation Points: 10
Solved Threads: 0
I have however modified the function so that if it has less than the designated words it will not do the array_pop
Ragnarok
Junior Poster in Training
94 posts since Mar 2004
Reputation Points: 10
Solved Threads: 0
Cool. Glad it's working for ya.
samaru
a.k.a inscissor
1,256 posts since Feb 2002
Reputation Points: 262
Solved Threads: 18