用 Dot(.) 替换逗号 (,) RegEx php
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6346997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace Comma(,) with Dot(.) RegEx php
提问by daniel__
i am trying this code but i get this error: No ending delimiter '/' found
我正在尝试此代码,但出现此错误: No ending delimiter '/' found
$form = " 2000,50";
$salary = preg_replace('/',', '.'/', $form); // No ending delimiter '/' found
echo $salary;
I am not sure about the regex validation.
我不确定正则表达式验证。
回答by BoltClock
Regex is overkill for replacing just a single character. Why not just do this instead?
正则表达式对于仅替换单个字符来说太过分了。为什么不这样做呢?
str_replace(',', '.', $form);
回答by Midas
$salary = preg_replace('/,/', '.', $form);
But yeah, you don't really want to match a patternbut a string which is constant, so simply use str_replace()
.
但是,是的,您并不是真的想匹配模式,而是匹配一个常量字符串,所以只需使用str_replace()
.
回答by ArtoAle
You can simply use
你可以简单地使用
str_replace(',','.',$form);
回答by Hyman V.
I don't understand your parameters -- I'm not sure what's supposed to be in the string and what isn't. But for preg_replace, the search pattern should be a string, and with the string also begin and end with a delimiter (typically '/'). I think it's redudant to need slashes round the search string when it's already inside a string, but that's how it works.
我不明白你的参数——我不确定什么应该在字符串中,什么不是。但是对于preg_replace,搜索模式应该是一个字符串,并且字符串也以分隔符(通常是'/')开始和结束。我认为当搜索字符串已经在字符串中时需要在搜索字符串周围加上斜线是多余的,但这就是它的工作原理。
The second parameter should be a string containing the full stop and nothing else. This gives:
第二个参数应该是一个包含句号的字符串,没有别的。这给出:
$salary = preg_replace( '/,/' , '.' , $form);
$salary = preg_replace( '/,/' , '.' , $form);
Other people are correct that str_replace will be fine for turning one character into another, but if the replacement you want gets more complicated preg_replace will be reasonable.
其他人认为 str_replace 可以将一个字符转换为另一个字符是正确的,但是如果您想要的替换变得更复杂 preg_replace 将是合理的。
回答by Rob Raisch
The '/' in your string is used as a start-of-regex delimiter so you need to escape it. The correct line should read:
字符串中的“/”用作正则表达式的开始分隔符,因此您需要对其进行转义。正确的行应该是:
$salary = preg_replace('\/',', '.'/', $form);
I'm also curious why the second param is ', ' . '/' rather than ', /'.
我也很好奇为什么第二个参数是 ', ' 。'/' 而不是 ', /'。
EDIT
编辑
Ahh I see now, the line should read:
啊,我现在明白了,这行应该是:
$salary = preg_replace( '/,/', '.', $form);
I was confused because the first comma in your example should be a '.' to concat the string.
我很困惑,因为您示例中的第一个逗号应该是“。” 连接字符串。