2013-03-05 41 views
1

修改SimplePie的項目輸出我正在使用SimplePie顯示RSS源中的第一項的標題,該項目在我要求監視的立法機構中的某個法案出現問題時進行更新。這個立法機構發佈我可以用SimplePie獲取的RSS提要,並顯示給需要這些信息的人。 SimplePie代碼完美地完成了它的工作。使用preg_replace

但是,我想在使用preg_replace回顯之前修改輸出,以便將其清理一些。

的作品

我原來的代碼了SimplePie如下:

<?php $max = $feed->get_item_quantity(1); 
     for ($x = 0; $x < $max; $x++): 
      $item = $feed->get_item($x); 
?> 
<?php echo $item->get_title(); ?> 
<?php endfor; ?> 

我嘗試使用這樣的:

<?php $max = $feed->get_item_quantity(1); 
     for ($x = 0; $x < $max; $x++): 
      $item = $feed->get_item($x); ?> 
<?php $str = '/([0-9]+) &#8211;/'; 
     $str = preg_replace('/([0-9]+) &#8211;/', '', $str); 
?> 
<?php echo $item->get_title(); ?> 
<?php endfor; ?> 

...但它不是我的修改輸出。它似乎沒有做任何事情。我沒有得到錯誤,但它不起作用。

的實際輸出(這只是一個項目名稱)目前看起來是這樣的:

07 - 2013年3月1日 - 傳遞給規則委員會二讀。

該開頭的兩位數字是無關信息。我想消除它和它後面的連字符,所以標題會如下出現:

2013年3月1日 - 傳遞給規則委員會進行二讀。

雖然,理想情況下,我想應該是這樣的:

(2013年3月1日)傳遞給規則委員會二讀。

關於如何使這項工作的建議?

回答

0

請試試這個: -

$str = '07 – March 1, 2013 – Passed to Rules Committee for second reading.'; 
$str = preg_replace('/(^[0-9]+) –/', '', $str); 
echo $str; 

輸出: -

March 1, 2013 – Passed to Rules Committee for second reading. 

代碼: -

<?php $max = $feed->get_item_quantity(1); 
      for ($x = 0; $x < $max; $x++): 
       $item = $feed->get_item($x); ?> 
    <?php $str = '/([0-9]+) &#8211;/'; <<======= your title string is regular expression here 
      // assign your title string here 
      $str = preg_replace('/([0-9]+) &#8211;/', '', $str); 
    ?> 
    <?php echo $item->get_title(); ?> 
    <?php endfor; ?> 

更新的代碼: -

<?php 
       $max = $feed->get_item_quantity(1); 
       for ($x = 0; $x < $max; $x++): 
         $item = $feed->get_item($x); 
         $title_str = $item->get_title(); 
         $title = preg_replace('/(^[0-9]+) –/', '', $title_str); 

         $pattern = '/(\w+) (\d+), (\d+)/i'; 
         $replacement = '(${1} 1, $3)'; 
         $title = preg_replace($pattern, $replacement, $title); 
         echo $title; 
       endfor; 
    ?> 

對於所需輸出: -

$string = 'March 1, 2013 - Passed to Rules Committee for second reading.'; 
$pattern = '/(\w+) (\d+), (\d+)/i'; 
$replacement = '(${1} 1, $3)'; 
echo preg_replace($pattern, $replacement, $string); 

輸出: -

(March 1, 2013) – Passed to Rules Committee for second reading. 
+0

試過了(不得不使用連字符連字符),它的工作原理!你會推薦什麼樣的正則表達式來在日期周圍加上括號,這樣看起來像這樣? (2013年3月1日)通過規則委員會二讀 – Seascape 2013-03-05 05:18:58

0

需要修改您這樣的代碼,你已經使用了$ STR應該包含您希望修改字符串。

<?php $max = $feed->get_item_quantity(1); 
     for ($x = 0; $x < $max; $x++): 
      $item = $feed->get_item($x); 
echo preg_replace('/([0-9]+) &#8211;/', '', $item->get_title()); ?> 
<?php endfor; ?>