如何在未知值上使用preg_replace_callback?

I got some great help today with starting to understand preg_replace_callback with known values. But now I want to tackle unknown values.

$string = '<p id="keepthis"> text</p><div id="foo">text</div><div id="bar">more text</div><a id="red"href="page6.php">Page 6</a><a id="green"href="page7.php">Page 7</a>';

With that as my string, how would I go about using preg_replace_callback to remove all id's from divs and a tags but keeping the id in place for the p tag?

so from my string

<p id="keepthis"> text</p>
<div id="foo">text</div>
<div id="bar">more text</div>
<a id="red"href="page6.php">Page 6</a>
<a id="green"href="page7.php">Page 7</a>

to

<p id="keepthis"> text</p>
<div>text</div>
<div>more text</div>
<a href="page6.php">Page 6</a>
<a href="page7.php">Page 7</a>

There's no need of a callback.

$string = preg_replace('/(?<=<div|<a)( *id="[^"]+")/', ' ', $string);

Live demo

However in the use of preg_replace_callback:

echo preg_replace_callback(
    '/(?<=<div|<a)( *id="[^"]+")/',
    function ($match)
    {
        return " ";
    },
    $string
 );

Demo

For your example, the following should work:

$result = preg_replace('/(<(a|div)[^>]*\s+)id="[^"]*"\s*/', '\1', $string);

Though in general you'd better avoid parsing HTML with regular expressions and use a proper parser instead (for example load the HTML into a DOMDocument and use the removeAttribute method, like in this answer). That way you can handle variations in markup and malformed HTML much better.