我想從使用php的字符串中獲取子字符串的位置。我可以使用strpos()
,但它只返回第一次出現。我怎樣才能得到多次出現的位置。在字符串中找到多個子字符串
1
A
回答
1
來自:http://www.php.net/manual/en/function.strpos.php#108426
function strpos_r($haystack, $needle)
{
if(strlen($needle) > strlen($haystack))
trigger_error(sprintf("%s: length of argument 2 must be <= argument 1", __FUNCTION__), E_USER_WARNING);
$seeks = array();
while($seek = strrpos($haystack, $needle))
{
array_push($seeks, $seek);
$haystack = substr($haystack, 0, $seek);
}
return $seeks;
}
這將返回與OCCURENCES的位置的陣列。
0
從手冊中,評論中有這樣的功能。 strpos的
function strpos_recursive($haystack, $needle, $offset = 0, &$results = array()) {
$offset = strpos($haystack, $needle, $offset);
if($offset === false) {
return $results;
} else {
$results[] = $offset;
return strpos_recursive($haystack, $needle, ($offset + 1), $results);
}
}
0
第三個參數,有$偏移,您可以使用:
$positions_of_string = array();
$str_to_find = "string to find";
$str_length = strlen($str_to_find);
$last_found = 0 - $str_length;
while(false !== $last_found) {
$last_found = strpos($the_string, $str_to_find, $last_found+$str_length);
if(false !== $last_found)
$positions_of_strings[] = $last_found;
}
相關問題
- 1. 如何找到一個字符串的多個子字符串,但如果找不到多個子字符串,仍然會返回許多子字符串
- 2. 在行中找到第n個字符串或子字符串
- 3. 查找字符串中的多個子字符串
- 4. 在字符串中找不到子串
- 5. 如何從n個字符串中找到子字符串
- 6. js正則表達式在字符串中找到多個子字符串
- 7. 如何從Python中的字符串中找到多個子字符串
- 8. 批處理文件在字符串中找到子字符串
- 9. 如何在字符串中找到子字符串?
- 10. 如何在Objective-c字符串中找到子字符串
- 11. 在包含多個字符串的許多對象中查找子字符串
- 12. 找到另一個字符串內的多個字符串
- 13. 在輸入字符串中查找字符串中的子串
- 14. 如何找到多個字符串中最長的公共子字符串?
- 15. bash:在多個其他字符串中查找字符串
- 16. 如何找到兩個字符串之間的子字符串?
- 17. 找到一個子字符串中的
- 18. 在字符串中找到一個數組中的字符串
- 19. 在一個字符串中有多少次子字符串[Java]
- 20. 在java中將字符串分割成多個子字符串
- 21. 在字符串中查找字符串
- 22. 在字符串中查找字符串
- 23. 的Perl:字符串中子字符串或子字符串中
- 24. C找到字符串中的子字符串與指針
- 25. 在字符串內部找到子字符串
- 26. 在字符串中查找多個事件的子字符串[C++]
- 27. 測試單個字符串中的多個子字符串?
- 28. iOS如何在一個巨大的字符串中找到2個字符串之間的多個字符串?
- 29. 在java中找到字符串中第n個子字符串的出現?
- 30. 在C中找到一個字符串中的子字符串C
此功能是越野車,當*針* *是*草垛的前綴爲''strpos'returns 0'。 – Gumbo
非常感謝,它的工作很好。 –
沒問題 - 請將此答案標記爲已接受。 – Silox