I'm trying to use a more complex regex and preg_split on a string to get an array of all matches and keep the delimiter. Normally this would be simple, but trying to use PREG_SPLIT_DELIM_CAPTURE and having multiple sets of parentheses in my regex is proving to be difficult. I'll elaborate:
I want to parse an IP address in a line and break the whole line into an array so I can do something with only the IP specifically, but I want to display the entire line eventually (I'm applying formatting to the IP and then re-assembling and displaying the string). My regex for that is this (it checks for something that looks like an IP, but it doesn't check validity, I don't care at this point):
(((\d{1,3})\.){3}(\d{1,3}))
Now, my code for the time being is this: $ipv4regex = "/(((\d{1,3}).){3}(\d{1,3}))/";
if (contains_ipv4($line)){
$pieces = preg_split($ipv4regex, $line, 0, PREG_SPLIT_DELIM_CAPTURE);
print "<pre>";
print_r($pieces);
print "</pre>";
}
function contains_ipv4($val){
return (preg_match($ipv4regex, $val));
}
And here is a sample of my output (IP address changed, but still relevant):
Array
(
[0] => show arp results from
[1] => 10.10.15.120
[2] => 15.
[3] => 15
[4] => 120
[5] =>
)
How can I change it so that the output is as follows:
(
[0] => show arp results from
[1] => 10.10.15.120
[2] =>
)
Essentially I want to capture only the outer-most parentheses in my regex for PREG_SPLIT_DELIM_CAPTURE, and not the inner ones. I know that I can change my regex for this particular case, but I've got a "proper" IPv6 regex with a LOT of parentheses and I'm afraid that it will be near impossible to rewrite with only one set of parentheses on the outside. Could anyone help me out? I'd greatly appreciate it. Or, if there's an entirely different means to my end that I'm missing, feel free to point me in that direction.