PHP-当被类似的干草堆包围时,大海捞针搜索不起作用


PHP - Needle in a haystack search not working when surrounded by similar hay stacks

任何人都知道如何修改下面的刮刀以获得所需的结果:

Array ( [0] => Gold_Needle [1] => Silver_Needle )

代码可以在线运行@http://ideone.com/QATj5a

结果是:

Array ( [0] => this is a bunch of hay hay1= Gold_Needle [1] => Silver_Needle )

所需结果为:

Array ( [0] => Gold_Needle [1] => Silver_Needle )

使用$starts$ends数组构建如下的前瞻正则表达式:

(hay1='h*'K(?:.(?!hay1))*?(?= hay=Gold))|(hay2='h*'K(?:.(?!hay2))*?(?= hay=Silver))
  • RegEx演示

  • 代码演示

代码:

$haystack='Data set 1: hay2= this is a bunch of hay  hay1= Gold_Needle hay=Gold
             Data Set 2: hay2=Silver_Needle hay=Silver';
$needle1_Begin='hay1=';
$needle2_Begin='hay2=';
$needle1_End='hay=Gold';
$needle2_End='hay=Silver';
$starts = array($needle1_Begin,$needle2_Begin);
$ends = array($needle1_End,$needle2_End);
$re = array_reduce($starts, function($res, $e) use (&$ends) {
    $res .= '(' . $e . ''h*'K(?:.(?!' . $e . '))*?(?= ' . current($ends) . '))|';
    next($ends); return $res;} );
$re = '/' . substr($re, 0, -1) . '/';
if (preg_match_all($re, $haystack, $m))
   print_r($m[0]);

输出:

Array
(
    [0] => Gold_Needle
    [1] => Silver_Needle
)