I am attempting to hack about some sidebar code inside a Wordpress template I am developing. Essentially I have taken things i need within an output buffer and I am running regex regarding this to exchange bits using the code I want. Issue is my regex understanding is simply a little short on which I have to achieve.

The issue I am getting is really as such:

$output = preg_replace('/<\/li><li id=".*?" class="widget-container/', '<a href="top">Top</a></li><li><li id="[item from that find]" class="widget-container/', $input);

Right now because the code stands I'm able to determine what I want however it destroys individuals id characteristics when i can't capture them.

I am sure there's a means I'm able to do that to capture and employ it within the alternative however i aren't able to find something that informs me things i need or maybe I am using the wrong approach with preg_replace.

How do i make use of this to alter code without wrecking individuals unique ids?

Cheers men!

You should utilize a back reference. Capture the id using ( ) after which reference the capture with $-.. see below:

$output = preg_replace('/<\/li><li id="(.*?)" class="widget-container/', '<a href="top">Top</a></li><li><li id="$1" class="widget-container/', $input);

wrap the pattern you need to match in ( ) and employ $1

$pattern = '/<\/li><li id="(.*?)" class="widget-container/';
$replace = '<a href="top">Top</a></li><li><li id="$1" class="widget-container/'
$output = preg_replace($pattern, $replace, $input);