I am currently running a preg_match_all
on a string that is looking for phone numbers using regular expressions. When it finds a match it makes note of the offset position within the string.
preg_match_all Example:
preg_match_all('/\b\/?\d?[-.]?\s?\(?\d{3}\)?\s?[-.]?\d{3}[-.]?\d{4}\b/', $string, $matches, PREG_OFFSET_CAPTURE);
Using print_r
echo print_r($matches, true).BR;
Outputs:
Array
(
[0] => Array
(
[0] => Array
(
[0] => 666.666.6666
[1] => 1190
)
[1] => Array
(
[0] => 555-555-5555
[1] => 1206
)
)
)
The problem: How do I loop through the matches and echo out the number, and the offset position?
You could use a foreach loop :
foreach ($matches[0] as $match) { // use first array item to loop through since the matches are in its sub-array
echo "Number = " . $match[0] . " | Offset = " . $match[1] . "\r\n";
}
Output :
Number = 666.666.6666 | Offset = 1190 Number = 555.555.5555 | Offset = 1206