Uno Mein Ame
Uno Mein Ame

Reputation: 1090

regex replacement - number between nodes

This is my regex:

\^((<i><b>|<b><i>)(\d+)(\<\/b>\<\/i>|\<\/i>\<\/b>))?\s+/mi

It is supposed to catch <i><b>14</b></i> some text

The good news is that it catches <i><b>14</b></i> as \1 which is what I need for step 1 of the function.

The bad news is that I can't figure out how to write the replacement variable to catch 14 and replace it with number 1

What I tried was \21\4, where \2 stood for <i><b> and \4 stood for </b></i> but the whole thing gets interpreted as \21 not \2. I can't have the space after \2

What's the right way to write the replacement variable?

Upvotes: 2

Views: 40

Answers (2)

anubhava
anubhava

Reputation: 785631

You can use this lookaround based regex:

$re = '~(?:<[bi]>)*\b(\d+)\b(?:</[bi]>)*~m';
$str = preg_replace($re, '$0 :: $1', '<i><b>14</b></i>');
//=> <i><b>14</b></i> :: 14

Though it will be safer to parse your HTML using DOM parser and and then manipulate it.

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336418

To answer your question directly: In order to disambiguate backreference $2 and the number 1 from backreference $21, you can use braces:

${2}1

Upvotes: 1

Related Questions