donglian1384 2017-10-23 16:11
浏览 128
已采纳

如果模式不匹配,如何使preg_match_all返回一个空数组值?

Let's say we have the following data, with the code to match the pattern we'd like, in this case we're catching all numbers and unicode fractions.

$array = array('1 ½ cups','¼ cup','2 tablespoons', '½ cup', '1/3 cup',  '2 large', '1 ½ teaspoons', '2 tablespoons', 'Large egg', '1 teaspoon', '¼ teaspoon');

foreach($array as $arr){
    preg_match_all("/^(?:[\p{Pd}.\/\s-]*[\d↉½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑⅒⅟])+/um", $arr, $output);

    foreach($output[0] as $data){
        $try[] = $data;
    }
}

If we print_r($try) we get:

Array
(
    [0] => 1 ½
    [1] => ¼
    [2] => 2
    [3] => ½
    [4] => 1/3
    [5] => 2
    [6] => 1 ½
    [7] => 2
    [8] => 1
    [9] => ¼
)

There are 11 items in the array, one of them being complete text, Large egg in this example.

What I'm trying to do is make preg_match_all return an empty value for that iteration, so we'd get this instead:

Array
(
    [0] => 1 ½
    [1] => ¼
    [2] => 2
    [3] => ½
    [4] => 1/3
    [5] => 2
    [6] => 1 ½
    [7] => 2
    [8] =>
    [9] => 1
    [10] => ¼
)

What I've tried?

I looked over the preg_match_all manual but I wasn't able to find anything that could lead me to my answer, at this point I'm thinking it might have to be done over at the regex pattern, but I'm not sure at all at this point.

https://eval.in/885289

  • 写回答

2条回答 默认 最新

  • duanletao9487 2017-10-23 16:31
    关注

    It looks like each iteration can only return a maximum of one match, so preg_match_all with the inner foreach should not be needed. You can use preg_match and append a default blank value if there isn't a match.

    foreach($array as $arr){
        preg_match("/^(?:[\p{Pd}.\/\s-]*[\d↉½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑⅒⅟])+/um", $arr, $output);
    
        $try[] = $output[0] ?? '';
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)