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

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

什么时候开始都不晚,学到老
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 21
trim($string, '起') . '起'

这样不香吗?

2年前 评论
kinyou 2年前
lun1bz 2年前
Epona

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

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

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

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

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

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

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

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

2年前 评论
芝麻开门 (楼主) 2年前
$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));
2年前 评论
surest 2年前
Tacks (作者) 2年前
jarlon 2年前
Xianbing 2年前
Tacks (作者) 2年前

正则匹配数字

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

这样不香吗?

2年前 评论
kinyou 2年前
lun1bz 2年前

这个问一下 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)
2年前 评论
liaosp 2年前
晓飞 (作者) 2年前
"apple 笔记本 ¥3900起起,真便宜起起".replace(/(¥\d+)起起/, "$1起")

执行结果

file

2年前 评论