php注册表模式检查
我需要一个正则表达式来检查两个字符串并返回数据php注册表模式检查,php,regex,function,if-statement,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', ... ) 您可以尝试以下代码: $subj
$str = "/mypage/20/my-slug";
$subject = "/mypage/{id}/{slug}";
$pattern = '';
preg_match($pattern, $subject, $matches);
print_r($matches);
需要这个数组吗
array(
'id'=>20,
'slug'=>'my-slug',
...
)
您可以尝试以下代码:
$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);
在这里,您有自己的功能:
<?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));
你试过搜索它吗?只要将你的标题复制/粘贴到谷歌(即使有拼写错误)就会给你提供多个正确的例子和答案。对于这个模式,/mypage/{id}
找不到任何内容。首先学习如何在PHP中使用regex(只要搜索就可以找到),然后阅读一些关于regex模式的指南。这个问题表明你没有努力或试图自己解决这个问题。如果您在现有代码中遇到某些特定问题,我们将很乐意为您提供帮助,但这意味着您需要首先亲自尝试一些东西。检查模式需要/mypage/{id}