Question

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?

Was it helpful?

Solution

[ 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 . '"';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top