如何在PHP中查找字符串中字符的位置

php*_*per 5 php strpos

如何在php中查找字符串或句子中字符的位置

$char   = 'i';
$string = 'elvis williams';
$result = '3rd ,7th and 10th'.
Run Code Online (Sandbox Code Playgroud)

我试过strpos ..但没有用..

Arn*_*anc 15

这将为您提供$ string中$ char的位置:

$pos = strpos($string, $char);
Run Code Online (Sandbox Code Playgroud)

如果你想在字符串中所有出现的$ char的位置:

$positions = array();
$pos = -1;
while (($pos = strpos($string, $char, $pos+1)) !== false) {
    $positions[] = $pos;
}

$result = implode(', ', $positions);

print_r($result);
Run Code Online (Sandbox Code Playgroud)

在这里测试一下:http://codepad.viper-7.com/yssEK3