簡體   English   中英

匹配具有多個模式的字符串,並在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函數,如果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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM