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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?