匹配具有多个模式的字符串,并在 php 中返回匹配的模式


Match a string with multiple patterns and return the matched pattern in php

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

$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
}
你需要

准备一个正则表达式模式数组,并需要在foreachpreg_match中使用它,就像

$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
相关文章: