SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast weicool's Avatar
    Join Date
    Jul 2004
    Location
    USA
    Posts
    68
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Regular Expression Problem

    I'm trying to increment numbers in a string. For example, I'd like for
    "5 Golden Rings, 4 Calling Birds, 3 French Hens, 2 Turtle Doves"
    to turn into
    "6 Golden Rings, 5 Calling Birds, 4 French Hens, 3 Turtle Doves".

    I tried messing with regex, but couldn't figure out how I would do this. I attempted using preg_replace_callback with a function that increments whatever matched, but that didn't work either. Can someone help me out please?
    Pokemon Dream - The greatest Pokemon website of all...

  2. #2
    reads the ********* Crier silver trophybronze trophy longneck's Avatar
    Join Date
    Feb 2004
    Location
    Tampa, FL (US)
    Posts
    9,854
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    how about posting some of the stuff you tried? preg_replace_callback() is definitely the way to go.

  3. #3
    SitePoint Addict
    Join Date
    Dec 2005
    Posts
    262
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This should be rather elementary once you start using preg_replace-callback. What didn't work about what you tried?

  4. #4
    SitePoint Enthusiast weicool's Avatar
    Join Date
    Jul 2004
    Location
    USA
    Posts
    68
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    After a few hours of playing around with it, I finally got it to work.

    The preg call is this:
    preg_replace_callback('/(\d{1,})/', 'callback', $string);

    where $string is the string containing numbers to increment and callback is the name of the callback function, which is:

    function callback ($match) {
    return $match[1] + 1;
    }

    Guess I messed up on my regular expressions...still very uncomfortable with them. Gotta keep practicing.
    Pokemon Dream - The greatest Pokemon website of all...

  5. #5
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    callback looks like overkill to me.
    PHP Code:
    $new preg_replace('/\d+/e''$0+1'$old); 


Bookmarks

Posting Permissions

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