php regix patern check



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

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

需要这个数组

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

在这里,你有你的函数:

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

你可以尝试像代码一样:

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

最新更新