Mr. Llama
Mr. Llama

Reputation: 20899

Regex replace matched subexpression (and nothing else)?

I've used regex for ages but somehow I managed to never run into something like this.

I'm looking to do some bulk search/replace operations within a file where I need to replace some data within tag-like elements. For example, converting <DelayEvent>13A</DelayEvent> to just <DelayEvent>X</DelayEvent> where X might be different for each.

The current way I'm doing this is such:

$new_data = preg_replace('|<DelayEvent>(\w+)</DelayEvent>|', '<DelayEvent>X</DelayEvent>', $data);

I can shorten this a bit to:

$new_data = preg_replace('|(<DelayEvent>)(\w+)(</DelayEvent>)|', '${1}X${2}', $data);

But really all I want to do is simulate a "replace text between tags T with X".

Is there a way to do such a thing? In essence I'm trying to prevent having to match all the surrounding data and reassembling it later. I just want to replace a given matched sub-expression with something else.

Edit: The data is not XML, although it does what appear to be tag-like elements. I know better than parsing HTML and XML with RegEx. ;)

Upvotes: 1

Views: 584

Answers (1)

Mark Byers
Mark Byers

Reputation: 838376

It is possible using lookarounds:

$new_data = preg_replace('|(?<=<DelayEvent>)\w+(?=</DelayEvent>)|', 'X', $data);

See it working online: ideone

Upvotes: 2

Related Questions