繁体   English   中英

如何从PHP字符串中替换除数字(200、200.45等)以外的所有字符?

[英]How to replace all characters except a numeral (200, 200.45 etc.) from a string in php?

我只有几个字符串,我只需要提取php中的价格(显然是数字)。 用例如下:

     1) Rs. 23,459.45                 desired output = 23459.45
     2)Our best price 23,459.45       desired output = 23459.45 

等等

我给出了上述用例,以了解前面的字符可以是任何字符。

请帮忙!

它的:

$result = preg_replace('/[^0-9.]/', '', $string);

-但是请注意,由于字符串可能包含类似'foo . bar,baz . price 20.5 with .6 discount'因此在通常情况下,这不会验证数字或提供有效的结果'foo . bar,baz . price 20.5 with .6 discount' 'foo . bar,baz . price 20.5 with .6 discount' 'foo . bar,baz . price 20.5 with .6 discount'最终结果将不是有效数字。 因此,上面的代码回答了有关“如何替换”的问题,但不适合验证数字(如果您是目标,则没有提到)。

关于验证数字-这样的问题将是模棱两可的,因为如何转换..20.5.6 (上面的字符串的结果)并不明显。 但是,如果只需要检查一下,请在$result上使用is_numeric() ,如下所示:

$string = 'foo . bar,baz . price 20.5 with .6 discount';
$result = preg_replace('/[^0-9.]/', '', $string);
$result = is_numeric($result)?(float)$result:null;

怎么样:

$arr = array(
    'Rs. 23,459.45 ',
    'Our best price 23,459.45 ',
);
foreach($arr as $string) {
    $string = preg_replace('/^.*?(\d+),?(\d{3})(\.\d{2})?.*$/', "$1$2$3", $string);
    echo $string,"\n";
}

输出:

23459.45
23459.45

您可以使用它来验证上述字符串。 该函数何时取消Rs。 ,它将返回两个点,因此我使用ltrim删除了第一个点。

<?php

//$s = "Rs. 23,459.45"; 

$s= "Our best price 23,459.45";

echo $result = ltrim(preg_replace("/[^0-9.]+/", "", $s),'.');

?>

http://codepad.org/cyH5OWyE

暂无
暂无

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

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