duanchun1881 2018-01-13 13:52
浏览 64
已采纳

如何在content-disposition头中preg_match所有三种情况?

I'm trying to decode the content-disposition header (from curl) to get the filename using the following regular expression:

<?php
$str = 'attachment;filename="unnamed.jpg";filename*=UTF-8\'\'unnamed.jpg\'';
preg_match('/^.*?filename=(["\'])([^"\']+)\1/m', $str, $matches);

print_r($matches);

So while it matches if the filename is in single or double quotes, it fails if there are no quotes around the filename (which can happen)

$str = 'attachment;filename=unnamed.jpg;filename*=unnamed.jpg';

Right now I'm using two regular expressions (with if-else) but I just wanted to learn if it is possible to do in a single regex? Just for my own learning to master regex.

  • 写回答

4条回答 默认 最新

  • duandgfh0506 2018-01-13 17:45
    关注

    I will use the branch reset feature (?|...|...|...) that gives a more readable pattern and avoids to create a capture group for the quotes. In a branch-reset group, each capture groups have the same numbers for each alternative:

    if ( preg_match('~filename=(?|"([^"]*)"|\'([^\']*)\'|([^;]*))~', $str, $match) )
        echo $match[1], PHP_EOL;
    

    Whatever the alternative that succeeds, the capture is always in group 1.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办