PHP For 循环输出不正确的字符串位置数据

PHP For Loop Outputting Incorrect String Position Data

我有这个 for 循环我是 运行 一个有几百个字符的字符串。当我回显字符串位置时,位置返回为“10”,但循环的范围是 65 到 80。请参见下面的代码。

$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
    Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed 
    nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. 
    Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. 
    Vestibulum lacinia arcu eget nulla.";

for ($i = 80; $i > 65; $i--) {
    echo $i; //this outputs correctly-- i.e. "8079787776 etc..."
    if ($string[$i] == ' ') {
        $test = strpos($string, $string[$i]);
        echo $test;
        // $test is outputting "10".
        $leave = strstr($string, $test, true);
        echo $leave; // this outputs the text at position "10"
        // which verifies what I think is going on. 
        break;
    }
}

预期的结果是 space 最接近位置 80 的位置将显示在 echo $test 中,但显示的是位置 10。

我在这个问题上用头撞墙。有什么想法吗?

PHP docs描述了strpos函数的return值:

strpos — Find the position of the first occurrence of a substring in a string

因此,无论循环中的计数器值如何,此函数都会 return 字符串中第一次出现的位置。

你应该适当地使用偏移量:

$test = strpos($string, $string[$i], $i);