preg_replace how to remove all numbers except alphanumeric

How to remove all numbers exept alphanumeric, for example if i have string like this:

Abs_1234abcd_636950806858590746.lands

to become it like this

Abs_1234abcd_.lands

3 answers

  • answered 2019-06-11 23:34 Emma

    In this specific example, we can simply use _ as a left boundary and . as the right boundary, collect our digits, and replace:

    Test

    $re = '/(.+[_])[0-9]+(\..+)/m';
    $str = 'Abs_1234abcd_636950806858590746.lands';
    $subst = '$1$2';
    
    $result = preg_replace($re, $subst, $str);
    
    echo $result;
    

    Demo

  • answered 2019-06-12 00:28 sln

    It is probably done like this

    Find (?i)(?<![a-z\d])\d+(?![a-z\d])
    Replace with nothing.

    Explained:
    It's important to note that in the class [a-z\d] within assertions,
    there exists a digit, without which could let "abc901234def" match.

     (?i)                   # Case insensitive
     (?<! [a-z\d] )         # Behind, not a letter nor digit
     \d+                    # Many digits
     (?! [a-z\d] )          # Ahead, not a letter nor digit
    

    Note - a speedier version exists (?i)\d(?<!\d[a-z\d])\d*(?![a-z\d])


    Regex1:   (?i)\d(?<!\d[a-z\d])\d*(?![a-z\d])
    Completed iterations:   50  /  50     ( x 1000 )
    Matches found per iteration:   2
    Elapsed Time:    0.53 s,   530.56 ms,   530564 µs
    Matches per sec:   188,478
    
    
    Regex2:   (?i)(?<![a-z\d])\d+(?![a-z\d])
    Completed iterations:   50  /  50     ( x 1000 )
    Matches found per iteration:   2
    Elapsed Time:    0.91 s,   909.58 ms,   909577 µs
    Matches per sec:   109,941
    

  • answered 2019-06-12 07:55 The fourth bird

    For your example data, you could also match not a word character or an underscore [\W_] using a character class. Then forget what is matched using \K.

    Match 1+ digits that you want to replace with a empty string and assert what is on the right is again not a word character or an underscore.

    [\W_]\K\d+(?=[\W_])
    

    Regex demo