[英]Regex match with identical words
假設YES 、 OR和YES是隨機詞(前提是 2 個YES是相同的)並且僅用於表示:
我正在嘗試使用正則表達式在任何地方匹配YES 、 OR和YES ,條件是字符串必須僅匹配 2 YES 。
因此,如果我嘗試使用以下測試字符串:
yes or yes
no or yes
yes or no
maybe yes or yes
maybe yes or no
yes maybe or yes
maybe yes maybe yes maybe or
它應該只匹配以下內容:
yes or yes
maybe yes or yes
yes maybe or yes
maybe yes maybe yes maybe or
這是我正在處理的正則表達式查詢:
^(?=.*(?=\w.*yes)(?=\w.*or)(?=\w.*yes)).*
不幸的是,我的查詢仍然匹配no or yes
。 這是我的正則表達式鏈接:單擊此處
使用substr_count()
非正則表達式方式
<?php
$string = 'yes or yes
no or yes
yes or no
maybe yes or yes
maybe yes or no
yes maybe or yes
maybe yes maybe yes maybe or';
$array = explode("\n", $string);
$expected = [];
//print_r($array);
foreach($array as $line){
$words = substr_count($line,'yes');
if($words==2 && strpos($line, 'or') !== false ){
$expected[]= $line;
}
}
echo implode("\n",$expected);
輸出:
yes or yes
maybe yes or yes
yes maybe or yes
maybe yes maybe yes maybe or
演示: https : //3v4l.org/uL7fJ
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.