Strange strpos behaviour

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
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Strange strpos behaviour

Post by Ollie Saunders »

Can someone test this for me:

Code: Select all

function tokenPositions($msg)
{
    $token = '}';
    $i = strpos($msg, $token);
    while ($i !== false) {
        $arr[] = $i;
        $i = strpos($msg, $token, $i+1);
    }
    return print_r($arr, true);
}

$testTxt = "{label} is } an error{ {numErrors} i{sn't t}hat {ida}} {{tooltip} ";
echo tokenPositions($testTxt);
I get:

Code: Select all

Array ( [0] => 6 [1] => 11 [2] => 33 [3] => 43 [4] => 52 [5] => 53 [6] => 64 )
Which means strpos thinks the marked characters are == '}'

Code: Select all

{label} is } an error{ {numErrors} i{sn\'t that {ida}} {{tooltip}
      ^    ^                     ^         ^        ^^          ^
43 points to 't' ?!
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

<?php

function tokenPositions($msg)
{
    $token = '}';
    $i = strpos($msg, $token);
    while ($i !== false) {
        $arr[] = $i;
        $i = strpos($msg, $token, $i+1);
    }
    return $arr;
}

$testTxt = "{label} is } an error{ {numErrors} i{sn't t}hat {ida}} {{tooltip} ";

$arr = tokenPositions($testTxt);
echo $testTxt, PHP_EOL;

$pos = -1;
foreach($arr as $off)
{
	$len = $off - $pos;
	$pos += $len;
	echo str_pad('^', $len, ' ', STR_PAD_LEFT);
}

echo PHP_EOL;

print_r($arr);

?>
Works fine for me.

Code: Select all

[feyd@home]>php -v
PHP 5.1.2 (cli) (built: Jan 11 2006 16:40:00)
Copyright (c) 1997-2006 The PHP Group
Zend Engine v2.1.0, Copyright (c) 1998-2006 Zend Technologies
    with Xdebug v2.0.0beta5, Copyright (c) 2002, 2003, 2004, 2005, by Derick Rethans

[feyd@home]>php -r "include 'strpos.php';"
{label} is } an error{ {numErrors} i{sn't t}hat {ida}} {{tooltip}
      ^    ^                     ^         ^        ^^          ^
Array
(
    [0] => 6
    [1] => 11
    [2] => 33
    [3] => 43
    [4] => 52
    [5] => 53
    [6] => 64
)
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Omg I just realised I had two versions of the string one with the an extra }.
Well thanks feyd, I wouldn't have spotted it without that post of yours.
Post Reply