2011-08-16 47 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

相關問題