str_replace match only first instance

Posted by kylex on Stack Overflow See other posts from Stack Overflow or by kylex
Published on 2010-06-17T18:06:58Z Indexed on 2010/06/17 18:13 UTC
Read the original article Hit count: 349

Filed under:
|
|

A followup question to http://stackoverflow.com/questions/3063704/

Given the following POST data:

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

I'm wanting to remove ONLY the first instance of 2010-June-3, but the following code removes all the data.

$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'];

This echos:

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

It should echo:

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

© Stack Overflow or respective owner

Related posts about php

Related posts about preg-match-all