preg_replace()删除除尾随x之外的所有非数字字符


preg_replace() remove all non-numeric characters EXCEPT trailing x

我有以下代码来删除所有非数字字符:

$num = preg_replace('/'D/', '', $num);

我想让它删除所有数字字符,除了任何尾随的X(不区分大小写)。

例如:

s34kr = 34
xX4rx = 4x
rs5t928X = 5928X 

您可以使用前瞻性断言,再加上如下的替换:

preg_replace('/'D(?=.)|[^xX]$/', '', $num);

只有后面跟有另一个字符或不是"x"的尾随字符时,它才匹配非数字。

替代

你可以考虑匹配:

if (preg_match_all('/'d+|[xX]$/', $num, $matches)) {
     $num = join('', $matches[0]);
} else {
     $num = '';
}

这将匹配任意数字或尾随的"x",然后将捕获的匹配项连接在一起。

尝试:

$num = preg_replace('/(?:(?!'b'd+[xX]?'b).)*('b'd+[xX]?'b)?/', '$1', $num);