Increment a variable in preg_replace()?
Is there any way I can increment a variable for each replacement in a preg_replace() statement?
So basically if I have something like:
And after preg_replace() I would like to get:
with that incrementing "cut_1" and "cut_2" part.
<div id="cut_1">Text one</div>
<div id="cut_2">Text two</div>
I should mention I have tried things like:
But that doesn't work because the ++$x is just evaluated when preg_replace() is initially called.
preg_replace("/<cut>(.*)</cut>/i", "<div id=\"cut_".++$x."\">$1</div>", $inputText);
You could use preg_replace_callback() with a callback function that will do the incrementing via a static variable in the function.
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
How to Ask Questions the Smart Way
(not affiliated with this site, but well worth reading)
Looks like that's exactly what I need. Thanks!
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Tags for this Thread