2011-01-24 93 views
1

我正在從一個RSS提要收集信息的時間表系統。但是,當我嘗試從RSS中剝離必要的段時,preg_match將其視爲無效。preg_match問題

//Finds the day by stripping data from the myDragonnet RSS feed. 
function schedule($given_date) { 
    $url = "http://mydragonnet.hkis.edu.hk/schedule/day_schedule_rss.php?schedule_id=1"; 
    $rss = simplexml_load_file($url); 
    $date = date("~jS M Y~", strtotime($given_date)); 
    if($rss) { 
     foreach($rss->channel->item as $item) { 
      foreach ($item->title as $story) { 
       if (strpos($date, $story) !== false) { 
        preg_match("/Day (\d+)/", $story, $m); 
        break; // stop searching 
       } 
      } 
     } 
    } 
    return $m[1]; 
} 

功能:<?php echo schedule('01/24/2010'); ?>

這是我得到的錯誤 -

Warning: preg_match() [function.preg-match]: Unknown modifier '/' in ***/class.schedule.php on line 31 

回答

1

試試這個:

// Finds the day by stripping data from the myDragonnet RSS feed. 
function schedule($given_date) { 
    $url = "http://mydragonnet.hkis.edu.hk/schedule/day_schedule_rss.php?schedule_id=1"; 
    $rss = simplexml_load_file($url); 
    $date = date("jS M Y", strtotime($given_date)); 
    $found = false; 

    if($rss) { 
     foreach($rss->channel->item as $item) { 
      foreach ($item->title as $story) { 
       if (strpos($story, $date) !== false) { 
        if (preg_match('/Day (\d+)/i', $story, $m)) { 
         $found = true; 
         break; // stop searching 
        } 
       } 
      } 

      if ($found) 
      { 
       break; 
      } 
     } 
    } 
    return $m[1]; 
} 
2

這樣做的原因錯誤是preg_match預計其第一個參數(模式)被封閉在一對分隔符中說/the pattern/

所以改變:

preg_match($date, $story) 

preg_match('!'.preg_quote($date).'!', $story) 

而且它看起來像您使用preg_match只是搜索在另一個字符串的字符串。這是更好地使用像strposstrstr字符串搜索功能這樣的事情:

if (strpos($date, $story) === false) 
    continue; 

你可以重寫你的foreach環路

foreach ($item->title as $story) { 
     if (strpos($date, $story) !== false) { 
      echo $story;    
      break; // stop searching 
     } 
} 
+0

我將刪除! preg_match之前? – 2011-01-24 03:20:59

+0

不,你不...... – codaddict 2011-01-24 03:22:48

1

爲什麼不使用strstr()代替的preg_match的。它快得多! (Documentation