Home > front end >  How to fix while loop?
How to fix while loop?

Time:12-03

I’m trying to learn php. I thought of doing a simple app to divide a text for Twitter threads.

For simplicity, I want to divide the text at a space closest to 20 characters.

I tried using strpos() with offset like this:

$str = "The main application of de Sitter space is its use \in general relativity, where it serves as one of the simplest mathematical models of the universe;

while ($pos < 20) {
    $findme = ' ';
    $pos = strpos($str, $findme);
    $posOffset = $pos 1;
    $pos = strpos($str, $findme, $posOffset);
}

But this goes into an infinite loop?

What am I doing wrong.

CodePudding user response:

The issue with your original implementation is that you always reset the value of $pos to the first match with the first call to strpos(). So from 8 to 3 with each new iteration of your loop. So you actually never search beyond the second blank in the string. Which of course means that the loop will never terminate, since you always search in the same first 9 characters of the input string.


That probably is what you are looking for:

<?php
$input = "The main application of de Sitter space is its use \in general relativity, where it serves as one of the simplest mathematical models of the universe.";
$output=[];

do {
    $pos = 0;
    do {
        // note: we add a trailing blank to the end of the search subject to guarantee a match
        $pos = strpos($input . ' ', ' ', $pos   1);
    } while  ($pos < 20);
    $output[] = substr($input, 0, $pos);
    $input = substr($input, $pos   1);
} while (strlen($input) > 0);

print_r($output);

The output is:

Array
(
    [0] => The main application
    [1] => of de Sitter space is
    [2] => its use \in general relativity,
    [3] => where it serves as one
    [4] => of the simplest mathematical
    [5] => models of the universe.
)

Note however that searching for ' ' (the space character) is not really a robust strategy. Instead you should search for any white space character there is. Which includes tab characters for example, something your approach would be blind towards.

  •  Tags:  
  • php
  • Related