php - 一位数的正则表达式捕获两位数?
问题描述
此正则表达式捕获两位数的数字:
如果我有 y11 它仍然会捕获它,如何仅匹配 y0、y1、y2、y3、y4、y5、y6、y7、y8、y9 ?在数字之后可能有一个空格或一个字母或一个点。
preg_replace('/y([1-9]{1})/', 'y0$1', $string)
解决方案
我会匹配 pattern 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
推荐阅读
- batch-file - 更改目录后执行命令
- angular - 如何在 Angular6 中为响应式表单控件设置值?
- javascript - 如何使用 HTML、CSS 或 Javascript 在用户点击移动设备时创建反应?
- aspnetboilerplate - 如何使用 AbpODataEntityController 登录
- html - 悬停在与包装器相同的背景色上
- electron - 自定义框架菜单栏 - 电子
- jquery - 如何在锚链接上使用ajax
- firebase - 访问当前位置并将其发送到 firebase
- javascript - 我想为 Azure IoT Hub 或 Cosmos 创建一个包含嵌套对象的 JSON 字符串
- laravel - redis中有哪些高级缓存策略