Page 1 of 1

ow do i look for the position of some substring?

Posted: Sun Jan 25, 2004 5:59 am
by pelegk2
say i have this string
"asdasd123cvberwt123bdty123fdg"
and i want to find the start position of every place with "123"
how do i do that?
thansk in advance
peleg

Posted: Sun Jan 25, 2004 8:37 am
by Gen-ik
Run a loop and use strpos() to find the positions off a string within a string.

Code: Select all

<?php

$string = "asdasd123cvberwt123bdty123fdg";
$find = "123";
$offset = 0;

while($offset !== false)
{
    $position = strpos($string, $find, $offset);
    if($position !== false)
    {
        $pos[] = $position;
        $offset = $position;
    }
    else
    {
        $offset = false;
    }
}

foreach($pos as $key => $value)
{
    echo "Position {$key} = {$value}";
}

?>
That should work but it's worth checking out [php_man]stristr[/php_man] in the manual anyway.