dou4064 2013-07-23 19: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-23 22: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][*]"
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部