View Full Version : Making a text segement a variable for loop.

09-29-2004, 10:06 PM
Hey everyone, new to PHP, and having issues with this, and none of my PHP buddies are online to help me out, so I was hoping someone on here might be able to tell me real quick. I don't think what I'm trying to do is hard. Or maybe it is. At the bottom of the code, there's a chunk that makes a "text segement" for a longtext field in the database. I need to make it so that it is a variable that I can loop.

Can anyone help me format it to a variable that I can loop? Sounds simple to me, but I can't figure it out, but I've only been at PHP for a few weeks, so I'm still trying to figure it all out.

Thanks in advance for any help you can give me!




@mysql_select_db($database) or die("Unable to select databse");

$query="SELECT * FROM stories";




while ($i < $num) {



$str = "$story";
$no_of_words = 20;
$str_array = split(" ",$str,$no_of_words+1);
if(count($str_array)>$no_of_words) {
for($i=0; $i < $no_of_words; $i++) {
echo $str_array[$i]." "; }
echo "<b>...........(more)</b>";}



09-30-2004, 08:16 AM
what do you mean by "a variable that i can loop" ? Do you wanna repeat the value of that variable or so to make a long text ? Like

$text = 'bla';
$longtext = str_repeat($text, 10000);

09-30-2004, 09:21 AM
My stray guess would be that he would want to display the first 20 words and a more link if the text is longer.
That does not require a loop:

$story = 'This is my ultra long text of which I want to see only the first 20 words. I will try to get it working without loops.';

$story = explode(' ', $story, 21);
$rest_of_story = array_pop($story);
$cut_stroy = implode(' ', $story) . '... More';
print $cut_stroy;
print '<br>' . "\n" . $rest_of_story;

You will need some sort of regex to avoid multiple spaces put together and you could trim() all those whitespaces from the beginning and end of the text.

10-02-2004, 03:31 PM
preg_replace('/\s{2,}/', ' ', $story); should work to remove double spaces. (or more.)