Question

$text = $_POST['text'];  
$find = $_POST['find'];
$offset = 0;
while ($offset < strlen($text))
{
   $pos = strpos($text, $find, $offset);
   $offset += strlen($find);
   echo "$find found in $pos <br>";
}

There is something wrong with this program. All I want to do is print all the positions in which $find is located in $text.

Tell me what the problem is. Try not to change the while condition. Thanks in advance.

Was it helpful?

Solution

First of all you need to break out of your loop if its not found. And secondly, what I think you want to do is to jump to the point in the $text just after where you found the last $find:

$text = $_POST['text'];  
$find = $_POST['find'];
$offset = 0;
while ($offset < strlen($text))
{
   $pos = strpos($text, $find, $offset);
   // $offset += strlen($find); // removed
   if ( $pos===false ) break;
   $offset = $pos+1;
   echo "$find found in $pos <br>";
}

OTHER TIPS

Another, more compact way to do this would be something like this:

while ( ($pos=strpos($text,$find,$offset)) !== false) {
    echo "$find found in $pos <br>";
    $offset = $pos+1;
}

Why not use a regex like this:

$text = 'hello world, I want to find you world';
$find = 'world';

preg_match_all('/'.preg_quote($find, '/').'/', $text, $matches, PREG_OFFSET_CAPTURE);
echo '<pre>';
print_r($matches);
echo '</pre>';

Return:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => world
                    [1] => 6
                )

            [1] => Array
                (
                    [0] => world
                    [1] => 32
                )

        )

)

To get the same output use this:

$text = $_POST['text'];  
$find = $_POST['find'];
preg_match_all('/'.preg_quote($find, '/').'/', $text, $matches, PREG_OFFSET_CAPTURE);
foreach ($matches[0] as $match) {
    echo "$find found in {$match[1]}<br>";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top