问一下大家PHP字符串处理的问题, "¥3900起起",怎么处理成"¥3900起"?

接了一个旧项目,发现数据库里边的字段内容有问题,多了一个起字,
但是这个3900是不同的,有的是4900起,有的是5900等等,每个数值都不同,问一下大家怎么处理,谢谢大家!

什么时候开始都不晚,学到老
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 21
trim($string, '起') . '起'

这样不香吗?

1年前 评论
kinyou 1年前
lun1bz 1年前
Epona

str_replace($string, "起起", "起") ?

1年前 评论
Wsmallnews 1年前
芝麻开门 (楼主) 1年前
Mutoulee

每个人的方法思路可能都不一样,但是可能都殊途同归,比如:

1、先从字符串开头处理“¥”,有这个字符就替换为空,没有就忽略;

2、强制转整型(或浮点型),(int)或比如intval();

3、再统一组装,开头需要“¥”就加上,不要就算了,结尾要一个“起”还是两个“起”,自己决定;

1年前 评论
芝麻开门 (楼主) 1年前

有没一种可能 把这些有问题的内容改掉

1年前 评论
芝麻开门 (楼主) 1年前
$list = [
    '¥5000起',
    '¥3900起起',
    '¥2000',
    '¥999起起',
];

/**
 * It replaces the string '起起' with '起' and adds '起' to the end of the string if it's not already there
 * 
 * @param array list The array to be processed.
 * 
 * @return array The array with the modified strings.
 */
function handleUp(array $list) :array {
    foreach($list as &$item) {
        /* Replacing the string '起起' with '起'. */
        $item = str_replace('起起', '起', $item);

        /* Checking if the last character of the string is not '起' and if it is not, it adds '起' to the end of the string. */
        if(mb_substr($item, -1) != '起') {
            $item .= '起';
        }

    }
    unset($item);

    return $list;
}

var_dump(handleUp($list));
1年前 评论
surest 1年前
Tacks (作者) 1年前
jarlon 1年前
Xianbing 1年前
Tacks (作者) 1年前

正则匹配数字

$str = '¥3900';
preg_match_all('/\d+/',$str,$arr);
print_r($arr);
1年前 评论
trim($string, '起') . '起'

这样不香吗?

1年前 评论
kinyou 1年前
lun1bz 1年前

这个问一下ChatGPT就好了 :see_no_evil::

function modifyList($list) {
    foreach ($list as &$item) {
        // 判断字符串中是否有两个起
        if (substr_count($item, '起') == 2) {
            // 使用 str_replace 函数去掉一个起
            $item = str_replace('起起', '起', $item);
        }
        // 判断字符串中是否没有起
        if (strpos($item, '起') === false) {
            // 在字符串末尾加上一个起
            $item .= '起';
        }
    }
    return $list;
}

// 测试
$list = [
    '¥5000起',
    '¥3900起起',
    '¥2000',
    '¥999起起',
];

print_r(modifyList($list));

运行结果和之前相同,输出:

Array
(
    [0] =>5000[1] =>3900[2] =>2000[3] =>999)
1年前 评论
liaosp 1年前
晓飞 (作者) 1年前
"apple 笔记本 ¥3900起起,真便宜起起".replace(/(¥\d+)起起/, "$1起")

执行结果

file

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!