Ben
Ben

Reputation: 62444

PHP Regex moving selection to different location in string

I currently have this regex:

$text = preg_replace("#<sup>(?:(?!</?sup).)*$key(?:(?!</?sup).)*<\/sup>#is", '<sup>'.$val.'</sup>', $text);

The objective of the regex is to take <sup>[stuff here]$key[stuff here]</sup> and remove the stuff within the [stuff here] locations.

What I actually would like to do, is not remove $key[stuff here]</sup>, but simply move the stuff to $key</sup>[stuff here]

I've tried using $1-$4 and \\1-\\4 and I can't seem to get the text to be added after </sup>

Upvotes: 0

Views: 128

Answers (2)

Morten Nilsen
Morten Nilsen

Reputation: 631

Try this;

$text = preg_replace(
  '#<sup>((?:(?!</?sup).)*)'.$key.'((?:(?!</?sup).)*)</sup>#is', 
  '<sup>'.$val.'</sup>\1\2', 
  $text
);

The (?:...)* bit isn't actually a sub-pattern, and is therefor not available using backreferences. Also, if you use ' rather than " for string literals, you will only need to escape \ and '

// Cheers, Morten

Upvotes: 1

Rok Kralj
Rok Kralj

Reputation: 48755

You have to combine preg_match(); and preg_replace();

  1. You match the desired stuff with preg_match() and store in to the variable.
  2. You replace with the same regex to empty string.
  3. Append the variable you store to at the end.

Upvotes: 0

Related Questions