我是PHP的新手,我遇到了问题。
我需要删除所有字符,因为符号(抱歉我的英文不好,我来自阿根廷)
我有这样的文字:
3,94€
我需要的文字如下:
3,94
我通过多种方式尝试了这一点,但它没有用。
答案 0 :(得分:1)
有几种方法可以做到这一点:
使用strpos:
$string = '3,94€';
echo substr($string, 0, strpos($string, '&'));
或使用strstr:
// Requires PHP 5.3+ due to the true (before_needle) parameter
$string = '3,94€';
echo strstr($string, '&', true);
或使用explode:
// Useful if you need to keep the € part for later
$string = '3,94€';
list($part_a, $part_b) = explode('&', $string);
echo $part_a;
或使用reset:
$string = '3,94€';
echo reset(explode('&', $string));
最适合您的情况是使用strpos
查找字符串中第一次出现的&
,然后使用substr
将字符串从开头返回到strpos
返回的值。
答案 1 :(得分:0)
您可以使用正则表达式:https://regex101.com/r/uY0kH3/1
它可以在preg_match()函数中使用。
答案 2 :(得分:0)
另一个可能性是清理数字然后围绕它:
<?php
//Option 1: with regular expresions:
$val = '3,94€';
$res = preg_replace('/[^0-9.,]/','',$val);
var_dump($res);
//Option 2: with filter functions:
$res2 = filter_var($val, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
var_dump($res2);
//Output: 3,948364
//If you want to round it:
$res = substr($res, 0, 4);
var_dump($res);
?>
答案 3 :(得分:-1)
您可以使用str_replace。
<?php
$string = 3,94€
$final = str_replace('€' ,'', $string);
echo $final;