duanjiyun7391 2012-08-29 15:15
浏览 92

PHP preg_split并仅将整个正则表达式保留为分隔符,忽略括号内部

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.

  • 写回答

2条回答 默认 最新

  • dtdd25012 2012-08-29 15:18
    关注

    You can desactivate parentheses capturing by adding ?: just after the open parentheses, for example :

    ((?:(?:\d{1,3})\.){3}(?:\d{1,3}))
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分