6

PHPで文字列または文内の文字の位置を見つける方法

$char   = 'i';
$string = 'elvis williams';
$result = '3rd ,7th and 10th'.

strpos を試しましたが、使い物になりません。

4

1 に答える 1

16

これにより、$string 内の $char の位置が得られます。

$pos = strpos($string, $char);

文字列内の $char のすべての出現位置が必要な場合:

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

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

print_r($result);

ここでテストしてください: http://codepad.viper-7.com/yssEK3

于 2011-08-16T11:26:54.937 に答える