ow do i look for the position of some substring?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
pelegk2
Forum Regular
Posts: 633
Joined: Thu Nov 27, 2003 5:02 am
Location: Israel - the best place to live in after heaven
Contact:

ow do i look for the position of some substring?

Post 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
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Post 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.
Post Reply