簡體   English   中英

精確的正則表達式與和號匹配

[英]Exact regex match with ampersand words

我如何不能僅將“軟件”與“軟件和框架”相匹配?

$skill = array("software & framework","communication skills","technology-based","software","technology");

$text = "software & framework and technology-based and excel technology- communication";

foreach ($skill as $skills) {

preg_match_all("~(?<![\w-])" . preg_quote($skills) . "(?![\w-])~i", $text, $matchWords);

foreach ($matchWords[0] as $matchWord) {

echo "<b>MatchWord:</b> " . $matchWord.  "<br>";

}

當前結果:

  • MatchWord:軟件和框架
  • MatchWord:基於技術
  • MatchWord:軟件

預期成績:

  • MatchWord:軟件和框架
  • MatchWord:基於技術

您需要動態構建帶有交替的單個模式:

$pattern = '~(?<![\w-])(?:' . implode('|', array_map(function($i) {
     return preg_quote($i, '~');
}, $skill)) . ')(?![\w-])~i';

然后,您可以提取匹配項:

if (preg_match_all($pattern, $text, $matchWords)) {
  print_r($matchWords[0]);
}

輸出: Array ([0] => software & framework [1] => technology-based )

注意 :如果未按長度將$skill數組中的迭代按長度降序排序,則需要使用以下方法進行此操作,例如:

usort($skill, function($a, $b) {
    return strlen($b) - strlen($a);
});

查看完整的PHP演示

暫無
暫無

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

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