www.webdeveloper.com
Results 1 to 4 of 4

Thread: Increment a variable in preg_replace()?

  1. #1
    Join Date
    Oct 2009
    Location
    Michigan
    Posts
    19

    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:

    Code:
    <cut>Text one</cut>
    <cut>Text two</cut>
    And after preg_replace() I would like to get:

    Code:
    <div id="cut_1">Text one</div>
    <div id="cut_2">Text two</div>
    with that incrementing "cut_1" and "cut_2" part.

  2. #2
    Join Date
    Oct 2009
    Location
    Michigan
    Posts
    19
    I should mention I have tried things like:

    Code:
    preg_replace("/<cut>(.*)</cut>/i", "<div id=\"cut_".++$x."\">$1</div>", $inputText);
    But that doesn't work because the ++$x is just evaluated when preg_replace() is initially called.

  3. #3
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,361
    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

    eBookworm.us

  4. #4
    Join Date
    Oct 2009
    Location
    Michigan
    Posts
    19

    resolved

    Looks like that's exactly what I need. Thanks!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles