我怎么能正则表达式呢?
how can i regexp this?
我可以用什么正则表达式来处理像
这样的字符串
2.3.5...9
4...
...
到
2.3.5.0.0.9
4.0.0.0
0.0.0.0
我已经试过了 preg_replace('/\.([^0-9])/', '.0', $mystring)
但没有成功,谢谢!
您当前的方法很接近,但要使其发挥作用,我们可以尝试使用环顾四周。替换:
(?<=^|\.)(?=\.|$)
与 0
.
$mystring = "2.3.5...9";
$output = preg_replace('/(?<=^|\.)(?=\.|$)/', '0', $mystring);
echo $output;
下面是对正则表达式逻辑的简要解释:
(?<=^|\.) position is preceded by either the start of the string, or another dot
(?=\.|$) position is followed by either the end of the string, or another dot
您可以使用preg_replace('/^(?=\.)|(?<=\.)(?=\.|$)/', '0', $mystring)
这涵盖了案例
- 字符串开头后跟点
- 两个点
- 点后跟字符串的结尾
如果输入字符串是 IPv4(类似)字符串(带或不带数字),则执行此操作:
echo preg_replace('~\B~', '0', '...'); // 0.0.0.0
我可以用什么正则表达式来处理像
这样的字符串2.3.5...9
4...
...
到
2.3.5.0.0.9
4.0.0.0
0.0.0.0
我已经试过了 preg_replace('/\.([^0-9])/', '.0', $mystring)
但没有成功,谢谢!
您当前的方法很接近,但要使其发挥作用,我们可以尝试使用环顾四周。替换:
(?<=^|\.)(?=\.|$)
与 0
.
$mystring = "2.3.5...9";
$output = preg_replace('/(?<=^|\.)(?=\.|$)/', '0', $mystring);
echo $output;
下面是对正则表达式逻辑的简要解释:
(?<=^|\.) position is preceded by either the start of the string, or another dot
(?=\.|$) position is followed by either the end of the string, or another dot
您可以使用preg_replace('/^(?=\.)|(?<=\.)(?=\.|$)/', '0', $mystring)
这涵盖了案例
- 字符串开头后跟点
- 两个点
- 点后跟字符串的结尾
如果输入字符串是 IPv4(类似)字符串(带或不带数字),则执行此操作:
echo preg_replace('~\B~', '0', '...'); // 0.0.0.0