views:

38

answers:

3

I'm trying to hack about some sidebar code in a Wordpress template I'm developing. Basically I've captured what I need in an output buffer and I'm running regex over it to replace bits with the code I need. Problem is my regex knowledge is just a bit short on what I need to achieve.

The problem I'm having is 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);

At the moment as the code stands I can find what I need but it destroys those id attributes as I can't capture them.

I'm sure there is a way I can do this to capture and use it in the replacement but I can't find anything that tells me what I need or if I'm taking the wrong approach with preg_replace.

How can I use this to change code without destroying those unique ids?

Cheers guys!

+1  A: 

You need to use a back reference. Capture the id using ( ) and then reference the capture with $1 ... 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);
Cfreak
I'd personally recommend the more precise id="([^"]+)" for clarity.
enobrev
Cheers, that did the trick. I thought it was along the lines of $1 but couldn't remember clearly. And to be honest I'd no idea that brackets were for that, I assumed it was for math style grouping.Thanks for you help.
Leonard
A: 

wrap the pattern you want to match in ( ) and use $1

Crayon Violent
A: 
$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);
Cags