此正则表达式捕获两位数字:
如果我有 y11 它仍然会捕获它,如何只匹配 y0, y1, y2, y3, y4, y5, y6, y7, y8, y9 ??数字后可能有一个空格或一个字母或一个点。
preg_replace('/y([1-9]{1})/', 'y0$1', $string)
最佳答案
我会匹配模式 y\d(?!\d)
,它匹配 y
后跟一个数字,它本身没有跟另一个数字.
$string = "y2";
echo $string . "\n";
$string = preg_replace("/y(\d)(?!\d)/", "y0$1", $string);
echo $string;
这打印:
y2
y02
正则解释:
y the letter 'y'
(\d) a single digit (capture it)
(?!\d) assert that what follows is either a non digit character OR
the end of the input
关于php - 单个数字的正则表达式捕获两位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66951744/