在另一个字符串[php]中找到一个字符串 - 由于某种原因匹配所有字符串?

时间:2013-01-04 22:43:56

标签: php regex

我正在尝试匹配表单提供的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" }

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

2 个答案:

答案 0 :(得分: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让我朝着正确的方向前进。谢谢,伊恩!

答案 1 :(得分:0)

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

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

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

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

if (preg_match($match1,$value) == 1 and preg_match($match2,$value) == 1) {
    [...]
}