PHP Find all occurrences of a substring in a string

后端 未结 9 1836
执念已碎
执念已碎 2020-12-01 01:56

I need to parse an HTML document and to find all occurrences of string asdf in it.

I currently have the HTML loaded into a string variable. I would just

9条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 02:14

    Salman A has a good answer, but remember to make your code multibyte-safe. To get correct positions with UTF-8, use mb_strpos instead of strpos:

    function strpos_all($haystack, $needle) {
        $offset = 0;
        $allpos = array();
        while (($pos = mb_strpos($haystack, $needle, $offset)) !== FALSE) {
            $offset   = $pos + 1;
            $allpos[] = $pos;
        }
        return $allpos;
    }
    print_r(strpos_all("aaa bbb aaa bbb aaa bbb", "aa"));
    

提交回复
热议问题