preg_match_all to get all occurrences of a string
Posted
by
i5z
on Stack Overflow
See other posts from Stack Overflow
or by i5z
Published on 2012-04-02T11:01:27Z
Indexed on
2012/04/02
11:29 UTC
Read the original article
Hit count: 167
php
|preg-match
I am trying to find offset of all occurrences with preg_match_all
e.g.
$haystack = 'aaaab';
$needle = 'aa';
preg_match_all('/' . $needle . '/', $haystack, $matches);
$matches is
Array
(
[0] => Array
(
[0] => Array
(
[0] => aa
[1] => 0
)
[1] => Array
(
[0] => aa
[1] => 2
)
)
)
It returns offset of first and second group of aa ("aa" "aa" "b") from the haystack, while I am expecting it to return "aa" starting at index 1 as well.
Array
(
[0] => Array
(
[0] => Array
(
[0] => aa
[1] => 0
)
[1] => Array
(
[0] => aa
[1] => 1
)
[2] => Array
(
[0] => aa
[1] => 2
)
)
)
Is there a way I can fix the regex or use some other function (which accepts regex) to get this done?
PS: I know strpos which can do this, but I have few more things to search for hence will go with preg_match_all.
© Stack Overflow or respective owner