2010-06-17 22 views
0

一個後續問題要Get all text between tags with preg_match_all() or better function?str_replace函數比賽只一審

考慮下列POST數據:

2010-June-3 
<remove>2010-June-3</remove> 
2010-June-15 
2010-June-16 
2010-June-17 
2010-June-3 
2010-June-1 

我想只刪除2010年六月3的第一個實例,但以下代碼將刪除所有數據。

$i = 1; 
$pattern = "/<remove>(.*?)<\/remove>/"; 
preg_match_all($pattern, $_POST['exclude'], $matches, PREG_SET_ORDER); 
    if (!empty($matches)) { 
     foreach ($matches as $match) { 
      // replace first instance of excluded data 
      $_POST['exclude'] = str_replace($match[1], "", $_POST['exclude'], $i); 
     } 
    } 

echo "<br /><br />".$_POST['exclude']; 

這回聲:

<remove></remove> 
2010-June-15 
2010-June-16 
2010-June-17 
2010-June-1 

應該呼應:

<remove>2010-June-3</remove> 
2010-June-15 
2010-June-16 
2010-June-17 
2010-June-3 
2010-June-1 

回答

3

您需要使用preg_replace()代替:

$_POST['exclude'] = preg_replace('/' . preg_quote($match[1], '/') . '/', "", $_POST['exclude'], 1, $i); 

後,$ _ POST [」變量排除']是limit變量,就像你在上面的鏈接中看到的一樣。

preg_quote()函數在日期字段中不是必需的,但由於它的變量,可能需要包含特殊的正則表達式字符。

+0

克里,你可能想爲'preg_quote'提供'$ delimiter'參數,以防萬一...以及實際調用'preg_replace'。 – salathe 2010-06-17 18:14:05

+0

好點 - 謝謝。我覺得很有趣/很傷心,我沒有用preg_replace – 2010-06-17 18:25:02

+0

代替代碼,就像冠軍一樣工作。謝謝! – kylex 2010-06-17 18:45:54