【问题标题】:PHP - Needle in a haystack search not working when surrounded by similar hay stacksPHP - 当被类似的干草堆包围时,干草堆搜索中的针不起作用
【发布时间】:2015-12-21 22:18:32
【问题描述】:

任何人都知道如何修改下面的刮板以达到预期的效果:

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 )

【问题讨论】:

    标签: php regex scrape scraper


    【解决方案1】:

    使用$starts$ends 数组构建一个前瞻正则表达式,如下所示:

    (hay1=\h*\K(?:.(?!hay1))*?(?= hay=Gold))|(hay2=\h*\K(?:.(?!hay2))*?(?= hay=Silver))
    

    代码:

    $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
    )
    

    【讨论】:

    • 感谢您的意见!代码中的“开始”和“结束”都会是变量,比如我把编辑后的代码@ideone.com/QATj5a放进去。像这样: $needle1_Begin='hay1='; $needle2_Begin='hay2='; $needle1_End='干草=金'; $needle2_End='干草=银';所以我不确定将它们放在正则表达式中。这些变量的数量将会增加。可能有几十个像 $needle55_Begin 等等。想法?谢谢!
    • 顺便说一句,我真的很难question。你有一个黄金正则表达式徽章,可以请你看一下吗? (事先)谢谢。
    • @ven:使用完整代码检查更新的答案。正则表达式保持不变,但需要一些 PHP 编码来构建正则表达式。
    猜你喜欢
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    相关资源
    最近更新 更多