php regix patern check

时间:2017-07-30 14:59:36

标签: php regex function if-statement

我需要一个正则表达式来检查两个字符串并返回数据

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

需要这个数组

array(
    'id'=>20,
    'slug'=>'my-slug',
    ...
)

2 个答案:

答案 0 :(得分:0)

您可以尝试代码:

$subject = "www.example.com?id=10&name=johnny";
$pattern = '/id=[0-9A-Za-z]*/'; //$pattern = '/id=[0-9]*/'; if it is only numeric.
preg_match($pattern, $subject, $matches);
print_r($matches);

答案 1 :(得分:0)

在这里,你有你的功能:

<?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));

您可以在此处测试:http://sandbox.onlinephpfunctions.com/code/8646e13bfc5a2b9ed5e2a5a2a9b9ddf1b0ab9db5