/** * Finds every occurance of the given needle in the haystack and returns their offsets * * @param String $needle The string being searched for * @param String $haystack The string that you trying to find the needle in * @param Boolean $ignoreCase Whether the search should be case sensitive * @return object Returns an array containing the found offsets. If the needle is not contained in the haystack, an empty array is returned */ function offsets($needle, $haystack, $ignoreCase = TRUE) { $ignoreCase = (bool) $ignoreCase; $needle = (string) $needle; $haystack = (string) $haystack; if (empty($needle)) { throw new \r8\Exception\Argument(0, 'needle', 'Must not be empty'); } if (!\r8\str\contains($needle, $haystack, $ignoreCase)) { return array(); } $count = $ignoreCase ? \r8\str\substr_icount($haystack, $needle) : substr_count($haystack, $needle); $found = array(); $offset = 0; $length = strlen($needle); for ($i = 0; $i < $count; $i++) { $found[] = $ignoreCase ? stripos($haystack, $needle, $offset) : strpos($haystack, $needle, $offset); $offset = end($found) + $length; } return $found; }
public function testSubstr_icount() { $this->assertEquals(2, \r8\str\substr_icount('This Is A Test', 'is')); $this->assertEquals(2, \r8\str\substr_icount('This Is A Test', 'Is')); $this->assertEquals(2, \r8\str\substr_icount('This Is A Test', 'IS')); $this->assertEquals(1, \r8\str\substr_icount('This Is A Test', 'is', 3)); $this->assertEquals(0, \r8\str\substr_icount('This Is A Test', 'is', 3, 3)); }