我想从使用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