【发布时间】:2017-04-08 04:22:44
【问题描述】:
我有以下字符串:
输入:
$str = "I want to remove only comma from this string, how ?";
我想从$str 中删除逗号,我是编程新手,不明白正则表达式的工作原理。
【问题讨论】:
-
您是否阅读过 RegEx 帮助或教程/这应该可以回答您的问题。
我有以下字符串:
输入:
$str = "I want to remove only comma from this string, how ?";
我想从$str 中删除逗号,我是编程新手,不明白正则表达式的工作原理。
【问题讨论】:
使用str_replace。
例子
$str = "I want to remove only comma from this string, how ?";
$str = str_replace(",", "", $str);
说明
如您所见,我们在 str_replace 中传递了 3 个参数
"," => 这个就是你要替换的
"" => 这是将替换第一个参数值的值。我们传递空白,因此它将逗号替换为空白
这是你要替换的字符串。
【讨论】:
正则表达式: (?<!\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
【讨论】:
/(?<!\d)\,(?!\d)/是什么吗?
.。我可以用str_replace 做到这一点,但我必须把它写在新行中。我怎样才能在一行代码中做到这一点?
, 和 . 而不使用 str_replace?
str_replace 是唯一的方法吗?