Tod
Tod

Reputation: 187

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

Upvotes: 0

Views: 145

Answers (3)

The fourth bird
The fourth bird

Reputation: 163227

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

Upvotes: 1

user557597
user557597

Reputation:

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

Upvotes: 1

Emma
Emma

Reputation: 27723

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

Upvotes: 1

Related Questions