简体   繁体   English

如何使用正则表达式提取php中的数字?

[英]how to extract number in php using regex?

If I want to extract only "7.20" from "$ 7.20", how can I do?? 如果我只想从“ $ 7.20”中提取“ 7.20”,该怎么办? I have try 我尝试了

preg_replace("[^0-9]", "", "$ 7.20");

but it is not work. 但这是行不通的。 It also shows $ 7.20... There is no difference... 它还显示$ 7.20 ...没有区别...

preg_replace('/[^.0-9]/', "", "$ 7.20");

Your regex needs to be delimited, start and end. 您的正则表达式需要定界,开始和结束。 Commonly / is used as a delimiter. 通常,/用作分隔符。

What you have above: [^0-9] 您在上方的内容: [^0-9]

The initial [ will be interpreted as a delimiter (in pair with ] at the end). 初始[将被解释为定界符(与]配对)。

This was looking to replace 0-9 literally at the beginning of the string. 该命令原本希望在字符串开头替换0-9

您也可以尝试sscanf ,通常更易于使用

sscanf( '$ 7.20', '$ %f' );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM