php preg_replace使用$结尾

时间:2017-06-25 08:21:44

标签: php regex preg-replace

我正试图从终点或逗号和零使用php

字符串是€69,00

代码为return preg_replace('/[\.,]{1}0*$/', '', $_price);

使用美元从右边搜索;找到multipl zero,直到找到第一个逗号或点(从右边开始)。用空字符串替换它。

原始请求:显示整数格式化的价格,作为无小数的底价。

€69,00中的字符串1和€69

€69,80中的字符串2和€69,80

€69,95中的字符串3以及€69,95

不知怎的,这不起作用

问题:当字符串已经格式化(不是数字)时,如何修复正则表达式以使整数值显示不带小数

2 个答案:

答案 0 :(得分:0)

尝试这个

preg_replace('/([€$])(\d+)([.,])(\d+)/', '$1$2', $_price);

答案 1 :(得分:0)

另一种变体是,00 只能

(€\d+)(?:[,.]00)

...并将其替换为$1,请参阅a demo on regex101.com

<小时/> PHP中的内容是:

<?php

$string = <<<DATA
String 1 in €69,00 and out €69
String 2 in €69,80 and out €69,80
String 3 in €69,95 and out €69,95
DATA;

$regex = '~(€\d+)(?:[,.]00)~';

$string = preg_replace($regex, "$1", $string);

echo $string;
?>