0

我正在尝试将表单提供的 UTC 时间和表单提供的事件名称字符串与从文件中读取的数组进行匹配。问题是它似乎总是匹配,即使它不应该匹配。文件的格式将始终保持不变,所以我知道我会在双引号内寻找一个值,所以在使用 strpos() 无法获得结果后,我尝试了 preg_match ...现在匹配所有内容。代码和示例输出如下($utc 和 $event_name)在我们到达这里时已经设置并正确):

$match1 = "/\"{$utc}\"/";
       $match2 = "/\"{$event_name}\"/";
       print "Match Values: $match1, $match2<p>";

foreach($line_array as $key => $value) {
   print "Value = $value<p>";

   if ((preg_match($match1,$value) == 1) and (preg_match($match2,$value) == 1))
   {
       print "Case 1 - False<p>";
   } else {
      print "Contains targets: $value<p>";
      //code to act on hit will go here
   }
}

这就是返回的内容:

Match Values: /"1371033000000"/, /"Another test - MkII "/

Value = { "date": "1357999200000", "type": "meeting", "title": "Plant and Animal Genome     Conference, San Diego, CA", "description": "NCGAS to present at Plant and Animal Genome   Conference, San Diego, CA", "url": "http://www.event1.com/" }

Contains targets: { "date": "1357999200000", "type": "meeting", "title": "Plant and Animal Genome Conference, San Diego, CA", "description": "NCGAS to present at Plant and  Animal Genome Conference, San Diego, CA", "url": "http://www.event1.com/" }

Value = { "date": "1357693200000", "type": "meeting", "title": "Testing Addition",  "description": "This is a fake event.", "url": "http://pti.iu.edu" }

Contains targets: { "date": "1357693200000", "type": "meeting", "title": "Testing Addition", "description": "This is a fake event.", "url": "http://pti.iu.edu" }

Value = { "date": "1371033000000", "type": "meeting", "title": "Another test - MkII", "description": "This is a fake event.", "url": "http://pti.iu.edu" }

Contains targets: { "date": "1371033000000", "type": "meeting", "title": "Another test - MkII", "description": "This is a fake event.", "url": "http://pti.iu.edu" }

我应该只匹配最后一个,但它们都匹配。我一直在玩正则表达式,似乎找不到合适的魔法。

4

2 回答 2

1

简化它并得到我想要的:

foreach($line_array as $key => $value) {
   print "Value = $value<p>";
   if (preg_match("/$utc/",$value) and preg_match("/$event_time/",$value))
   {
       print "Contains targets: $value<p>";
   } else {
       print "Case 1 - False<p>";
      //code to act on hit will go here
   }
}

但是答案 2 让我朝着正确的方向前进。谢谢,伊恩!

于 2013-01-07T15:12:26.557 回答
0

您不需要在双引号字符串中做任何奇怪的事情,只需将变量按原样放入...

$match1 = "/$utc/";
$match2 = "/$event_name/";

我怀疑您的正则表达式正在寻找零长度字符串。

此外,这一行不需要这么多括号......

if (preg_match($match1,$value) == 1 and preg_match($match2,$value) == 1) {
    [...]
}
于 2013-01-04T22:49:23.533 回答