dou4064 2013-07-24 03:32 采纳率: 100%
浏览 41
已采纳

PHP - Preg_match_all可选匹配

I'm having problems matching the[*] which is sometimes there and sometimes not. Anyone have suggestions?

$name = 'hello $this->row[today1][] dfh fgh df $this->row[test1] ,how good $this->row[test2][] is $this->row[today2][*] is monday'; 
echo $name."
"; 
preg_match_all( '/\$this->row[.*?][*]/', $name, $match ); 
var_dump( $match );  

output: hello $this->row[test] ,how good $this->row[test2] is $this->row[today][*] is monday

array (
 0 => 
  array (
   0 => '$this->row[today1][*]',
   1 => '$this->row[test1] ,how good $this->row[test2][*]',
   2 => '$this->row[today2][*]',
  ),
)

Now the [0][1] match takes on too much because it is matching until the next '[]' instead of ending at '$this->row[test]' . I'm guessing the [*]/ adds a wildcard. Somehow need to check if the next character is [ before matching to []. Anyone?

Thanks

  • 写回答

1条回答 默认 最新

  • donglikuang8145 2013-07-24 06:04
    关注

    [, ] and * are special meta characters in regex and you need to escape them. Also you need to make last [] optional as per your question.

    Following these suggestions following should work:

    $name = 'hello $this->row[today1][] dfh fgh df $this->row[test1] ,how good $this->row[test2][] is $this->row[today2][*] is monday'; 
    echo $name."
    "; 
    preg_match_all( '/\$this->row\[.*?\](?:\[.*?\])?/', $name, $match ); 
    var_dump( $match ); 
    

    OUTPUT:

    array(1) {
      [0]=>
      array(4) {
        [0]=>
        string(20) "$this->row[today1][]"
        [1]=>
        string(17) "$this->row[test1]"
        [2]=>
        string(19) "$this->row[test2][]"
        [3]=>
        string(21) "$this->row[today2][*]"
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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