kylex
kylex

Reputation: 14406

str_replace match only first instance

A followup question to Get all text between tags with preg_match_all() or better function?

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

Upvotes: 0

Views: 2547

Answers (1)

Kerry Jones
Kerry Jones

Reputation: 21838

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.

Upvotes: 3

Related Questions