2011-08-16 76 views
4

如何找到如何找到一个字符的位置在一个字符串中PHP

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

我试图strpos..but没有用在字符串或句子在PHP字符的位置..

+0

欢迎使用堆栈溢出。您可以使用工具栏按钮格式化源代码。 (ajreal已经为你做了这次。) –

回答

15

这会给你的$字符的位置在$字符串:

$pos = strpos($string, $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

+0

Dammit,我已经写了相同的代码几乎逐行7分钟后... –

+0

哇,这节省了我的时间..有没有可能重写递归方法的逻辑?? – phpdeveloper

相关问题