drpqxogph15436713 2017-07-30 14:59
浏览 7
已采纳

php正则表达式模式检查[关闭]

i need a regular expression for check two string and return data

$str = "/mypage/20/my-slug";
$subject = "/mypage/{id}/{slug}";
$pattern = ''; 
preg_match($pattern, $subject, $matches);
print_r($matches);

need this array

array(
    'id'=>20,
    'slug'=>'my-slug',
    ...
)
  • 写回答

2条回答 默认 最新

  • dongmi4927 2017-07-30 16:56
    关注

    Here, you have your function:

    <?php
    
    $str = "/mypage/20/my-slug";
    $subject = "/mypage/{id}/{slug}";
    
    function getQueryParameters($url, $pattern)
    {
        // Find first parameter:
        $pos=strpos($pattern, '{');
    
        if($pos===false)
        {
            return [];
        }
    
        $prefix=substr($pattern, 0, $pos);
    
        // Check for route
        if(substr($url, 0, $pos)!=$prefix)
        {
            return false;
        }
    
        $curlyBracesRegex='/'
            . '\{'              // One {
            . '([^\s}]+)'       // something inside curly braces, e.g. {foo}
                                // Excluding whitespaces (\s)
            . '\}'              // One }
            . '/';
    
        preg_match_all($curlyBracesRegex, $pattern, $matches);
    
        $parameters=[];
        foreach ($matches[0] as $index => $match)
        {
            $parameters[]=$matches[1][$index];
        }
    
        $matches=explode('/', substr($url, $pos));
    
        $queryParameters=array_combine($parameters, $matches);
    
        return $queryParameters;
    }
    
    print_r(getQueryParameters($str, $subject));
    

    You can test here: http://sandbox.onlinephpfunctions.com/code/8646e13bfc5a2b9ed5e2a5a2a9b9ddf1b0ab9db5

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

报告相同问题?

悬赏问题

  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题