Reputation: 14406
I have the following code to remove all non-numeric characters:
$num = preg_replace('/\D/', '', $num);
I'd like to make it so that it removes all numeric-characters except any trailing X (not case sensitive).
ex:
s34kr = 34
xX4rx = 4x
rs5t928X = 5928X
Upvotes: 2
Views: 1736
Reputation: 189
Try:
$num = preg_replace('/(?:(?!\b\d+[xX]?\b).)*(\b\d+[xX]?\b)?/', '$1', $num);
Upvotes: 0
Reputation: 173662
You could use look-ahead assertions, coupled with an alternation like this:
preg_replace('/\D(?=.)|[^xX]$/', '', $num);
It matches a non-digit only if followed by another character or a trailing character that's not 'x'.
Alternative
You could consider matching instead:
if (preg_match_all('/\d+|[xX]$/', $num, $matches)) {
$num = join('', $matches[0]);
} else {
$num = '';
}
This matches any number of digits or trailing 'x' and then joins the captured matches together.
Upvotes: 1