6

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

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

我试过strpos ..但没用..

4

1 回答 1

16

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

$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 回答