【问题标题】:Strip commas from a string in PHP [duplicate]从PHP中的字符串中删除逗号[重复]
【发布时间】:2017-04-08 04:22:44
【问题描述】:

我有以下字符串:

输入:

$str = "I want to remove only comma from this string, how ?";

我想从$str 中删除逗号,我是编程新手,不明白正则表达式的工作原理。

【问题讨论】:

  • 您是否阅读过 RegEx 帮助或教程/这应该可以回答您的问题。

标签: php regex


【解决方案1】:

使用str_replace

例子

$str = "I want to remove only comma from this string, how ?";
$str = str_replace(",", "", $str);  

说明

如您所见,我们在 str_replace 中传递了 3 个参数

  1. "," => 这个就是你要替换的

  2. "" => 这是将替换第一个参数值的值。我们传递空白,因此它将逗号替换为空白

  3. 这是你要替换的字符串。

【讨论】:

    【解决方案2】:

    正则表达式: (?<!\d)\,(?!\d)

    (\,|\.) 用于精确匹配 ,.

    (?!\d) 前面不应包含数字。

    (?<!\d) 后面不应包含数字。

    PHP 代码:

    <?php
    
    $str = "I want to remove only comma from this string, how. ? Here comma and dot 55,44,100.6 shouldn't be removed";
    echo preg_replace("/(?<!\d)(\,|\.)(?!\d)/", "", $str);
    

    输出:

    I want to remove only comma from this string how ? Here comma 55,44,100 shouldn't be removed
    

    【讨论】:

    • 你能给我解释一下/(?&lt;!\d)\,(?!\d)/是什么吗?
    • 嘿,现在我也想删除所有.。我可以用str_replace 做到这一点,但我必须把它写在新行中。我怎样才能在一行代码中做到这一点?
    • 是否要替换 ,. 而不使用 str_replace?
    • 是的,有可能吗? str_replace 是唯一的方法吗?
    • @kurniawan26 更新了我的帖子,您可以检查有效点和逗号是否被替换而不会中断数字
    猜你喜欢
    • 2015-10-28
    • 2016-04-19
    • 1970-01-01
    • 2013-07-29
    • 2022-01-11
    • 2012-03-09
    • 1970-01-01
    • 2015-07-27
    相关资源
    最近更新 更多