#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2005
    Posts
    227
    Rep Power
    16

    Removing . (periods) that match condition


    hi,

    I'm trying to make a regex for preg_replace that removes all . periods in a long $string - except - for those that are preceded by an optional $ plus 1 or more (mandatory) digits only.

    the one I've come up with:

    Code:
    $string = preg_replace("/((?:\$)?[^\d]+)\./","$1 ",$string);
    correctly replaces the period in:

    Code:
    1a.50
    $1a.50
    but misses the period in these:

    Code:
    a1.50
    $a1.50
    Can anyone help with that one??
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,965
    Rep Power
    9397
    Originally Posted by ryel01
    but misses the period in these:

    Code:
    a1.50
    $a1.50
    The way you described the problem, this is correct behavior.
    Both of those have a period, and each period is preceded by an optional $ plus 1 digit.
    Code:
    "1a.50"
    - found the . as "1a.50"
    - before is one digit? no
    verdict: replace
    
    "$1a.50"
    - found the . as "$1a.50"
    - before is one digit? no
    verdict: replace
    
    "a1.50"
    - found the . as "a1.50"
    - before is one digit? yes
    (- before that is an optional digit (already met the "1 or more" requirement)? no)
    (- before that is an optional $? no)
    verdict: do not replace
    
    "$a1.50"
    - found the . as "$a1.50"
    - before is one digit? yes
    (- before that is an optional digit (already met the "1 or more" requirement)? no)
    (- before that is an optional $? no)
    verdict: do not replace
    Perhaps you mean to say the $ is not optional?
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2005
    Posts
    227
    Rep Power
    16
    ah - I meant that what I had wasn't doing I wanted rather than it wasn't working right.

    but - I cracked it!

    Code:
    $string = preg_replace("/((\$)?[^0-9]+|[^0-9\$]+[0-9]+)\./","$1 ",$string);
    I'm on a roll - 2 regex's in 2 days!!!

IMN logo majestic logo threadwatch logo seochat tools logo