【问题标题】:Match a string with multiple patterns and return the matched pattern in php匹配具有多个模式的字符串并在php中返回匹配的模式
【发布时间】:2016-02-29 08:44:17
【问题描述】:

我正在编写一个函数,它将字符串与列表中的精确模式匹配并返回匹配的模式。

$patterns = array(
 'pages/{{name}}/{{id}}',
 'profile/{{id}}',
 'download_{{file}}-{{id}}'
);

现在我有一个字符串

$string = 'download_finalbuild_123';

我想比较这个字符串并返回匹配的模式。所以我使用了一个 foreach 语句

foreach($patterns as $pattern){
   $matched_pattern = '';
   if(match_pattern($pattern,$string){
     $matched_pattern = $pattern;
     break;
   }
}
echo 'Matched pattern is ' . $matched_pattern;

现在我想要一个函数 match_pattern,如果模式与字符串匹配则返回 true。

function match_pattern($first,$second){
   //Some magic here which return true if both parameters match
}

【问题讨论】:

  • 您只是在寻找preg_match吗?
  • @WiktorStribiżew 我尝试了 preg_match 但因为我在模式中有占位符,在字符串中有实际值。但我希望 php 匹配这个字符串匹配的模式
  • 我认为答案只是循环遍历模式数组并使用 preg_match 来查看是否有匹配项,然后将它们推送到结果数组。
  • @WiktorStribiżew 能否提供 match_pattern 函数的示例代码?

标签: php regex


【解决方案1】:

您需要准备一组正则表达式模式,并需要在foreachpreg_match 中像 as 一样使用它

$patterns = array(
 'pages\/[a-zA-Z]+\/[\d]+',
 'profile\/[\d]+',
 'download_[a-zA-Z]+_[\d]+'
);

$string = 'download_finalbuild_123';
$str = "";
foreach($patterns as $v){
    if(preg_match("/$v/",$string)){
        $str .= "Match string matches $v pattern";
    }
}

echo $str;

输出

Match string matches download_[a-zA-Z]+_[\d]+ pattern

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 2018-10-04
    • 1970-01-01
    相关资源
    最近更新 更多