How to use preg_replace_callback for unknown values?

Today I got a lot of help starting to understand preg_replace_callback with known values. But now I want to solve 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 this, as with my line, how can I use preg_replace_callback to remove all id from divs and tags, but keeping the id in place for the p tag?

so from my line

<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>
+3
source share
2 answers

No callback needed.

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

Live demo

However, when using preg_replace_callback:

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

Demo

+1
source

For your example, the following should work:

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

HTML (, HTML DOMDocument removeAttribute, ). , HTML.

0

All Articles