dongmei8460 2011-10-17 17:30
浏览 40
已采纳

正则表达式中逗号后的可选匹配项

I tried so hard and got so far but in the end it doesn't work!!

What I would like to do achieve is the following: I've got a preg_replace_callback function where I want to address my "dictionary" function.

I use my own "dictionary" tag:

<[general,username]>
<[general,username,1]>

this should call my function "dictionary". The function with it's ararguments is: dictionary($search,$section,$upper=null)

$search = filename
$section = array key
$upper = (int) 1 to 3

my callback function calls the function with the values from the "dictionary" tags.

for <[general,username]> I need
- $search = general
- $section = username
- $upper = null

but for <[general,username,1]> I want
- $search = general
- $section = username
- $upper = 1

I want my regular expression to always match 2 arguments (search and section) but have a third optional argument.

My regex:

/\<\[([^\[]+)\,([^\[]+)(\,[0-2])?\]\>/

but this doesn't work correctly. I get the following results:

for <[general,username]> I get

[0] => <[general,username]>
[1] => general
[2] => username

for <[general,username,1]> I get

[0] => <[general,username,1]>
[1] => general,username
[2] => 1

but I would like

[0] => <[general,username,1]>
[1] => general
[2] => username
[3] => 1

What am I doing wrong??

  • 写回答

3条回答 默认 最新

  • dongyi7513 2011-10-17 17:46
    关注

    Try this out:

    /\<\[([^\,]+)\,([^\,]+)(?:\,(\d+))?\]\>/
    
     - Item[0] => whole matching text
     - Item[1] => general
     - Item[2] => username
     - Item[3] => upper (if match)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的算法代码
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据