Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I use preg_replace_callback on unknown values?

Tags:

regex

php

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>
like image 572
Fred Turner Avatar asked May 01 '26 08:05

Fred Turner


1 Answers

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

like image 141
revo Avatar answered May 03 '26 20:05

revo