替换所有号码。消极的,积极的,用逗号,点等分隔
我有
$txt = "car -12 and dog 3.1416 and cat 98 and 4,12 and flowers = 0.1 and -75";
我喜欢
$txt = "car NUM and dog NUM and cat NUM and NUM and flowers = NUM and NUM";
请帮忙
答案 0 :(得分:1)
$a = preg_replace('/(-)?[0-9]+(.)?[0-9]+/','NUM',$txt);
答案 1 :(得分:0)
代码:(Demo)
$txt = "car -12 and dog 3.1416 and cat 98 and 4,12 and flowers = 0.1 and -75";
echo "EXPECT: car NUM and dog NUM and cat NUM and NUM and flowers = NUM and NUM\n";
echo "OUTPUT: ",preg_replace('~-?\d*[,.]?\d+~','NUM',$txt);
输出:
EXPECT: car NUM and dog NUM and cat NUM and NUM and flowers = NUM and NUM
OUTPUT: car NUM and dog NUM and cat NUM and NUM and flowers = NUM and NUM
故障:
~ #pattern delimiter
-? #match zero or one hyphen
\d* #match zero or more digits
[,.]? #match zero or one character in list: comma or dot
\d+ #match one or more digits
~ #pattern delimiter
如果此模式无法在所有输入字符串上执行,请更新您的问题以包含这些麻烦的字符串并留下评论,我会更新我的答案。
*注释:
.
内的[.]
无需转义即可进行字面处理。在角色类之外使用.
将需要以某种方式进行转义,否则将被视为"任何非换行符#34;。