0

I'm trying to replace the data attribute data-note with new values for an array.

$ids = array(
    '111' => '999', // replace data-note=111 with data-note= 999
    '222' => '888' // replace data-note=222 with data-note= 888
);

$html = '<span data-note="111" data-type="comment" name="a b c">el for 111 </span> text <span data-note="222" data-type="comment">el for 222 </span>';

foreach($ids as $oldKey => $newKey) {
    $patterns[] = '/data-note="[' . $oldKey . ']/';
    $replacements[] = '/data-note="[^"' . $newKey . ']"/';
}

echo preg_replace($patterns, $replacements, $html); // echos ... /data-note="[^"999]"/11" ...

What am I doing wrong?

2
  • What is wrong, you forgot to write the error Commented Apr 4, 2014 at 7:24
  • for string replacement you should use str_replace instead of preg_replace. it's much easier for string only replacement, without the need of regexes Commented Apr 4, 2014 at 7:28

1 Answer 1

2

[ and ] are specail character in a regex, you have to escape them:

$patterns[] = '/data-note="\[' . $oldKey . '\]/';

Moreover I guess you want simply:

$patterns[] = '/data-note="' . $oldKey . '"/';

Change also the replacement part:

$replacements[] = 'data-note="' . $newKey . '"';
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer but unfortunately, both those patterns return the original string with no changes.
@Cris: What is your expected result? The second one works for me unless you want other thing that <span /data-note="[^"999]"/ ... wich effectively produces an invalid html.
The end result should be <span data-note="999" ..... sorry I should have been more clear. The second one returns <span /data-note="999"/ (notice the extra slashes)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.