views:

39

answers:

1

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
+2  A: 

You need to use preg_replace() instead:

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

The variable after the $_POST['exclude'] is a limit variable, as you can see in the link above.

The preg_quote() function wasn't necessary in the date field, but because its a variable, it may be needed to include the special regular expression characters.

Kerry
Kerry, you might want to provide the `$delimiter` parameter for `preg_quote`, just in case... as well as actually call `preg_replace`.
salathe
Good point -- thanks. I find it funny/sad that I didn't replace the code with preg_replace
Kerry
That worked like a champ. Thank you!
kylex