Home  >  Article  >  Backend Development  >  Remove non-numeric characters except comma and dot via PHP regex

Remove non-numeric characters except comma and dot via PHP regex

藏色散人
藏色散人Original
2021-08-02 11:23:142928browse

从本文开始我会陆续给大家介绍PHP正则表达式的使用,当然面向的对象还是新手朋友们啦~希望能够通过一个个简单的小例子,让大家对正则表达式的使用越来越熟悉~

好的,咱们就从一个小问题开始~

给你一个字符串“$123,34.00A”,要求你用正则表达式删除除逗号和点以外的非数字字符,也就是说我们需要写一个PHP代码获取“123,34.00”,毕竟$A就属于除逗号和点以外的非数字字符。

非常简单啦~

上代码:

<?php
$str1 = "$12,334.00A";
echo preg_replace("/[^0-9,.]/", "", $str1)."\n";

没看错,这么简短的两行代码就可以完成我们的要求:

运行结果:

Remove non-numeric characters except comma and dot via PHP regex

搞定!

这里就是介绍一个重要的函数preg_replace,该函数能执行一个正则表达式的搜索和替换。

其语法是“mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )”,表示搜索 subject 中匹配 pattern 的部分, 以 replacement 进行替换。

其中几个参数具体表示:

$pattern: 要搜索的模式,可以是字符串或一个字符串数组。

$replacement: 用于替换的字符串或字符串数组。

$subject: 要搜索替换的目标字符串或字符串数组。

$limit: 可选,对于每个模式用于每个 subject 字符串的最大可替换次数。 默认是-1(无限制)。

$count: 可选,为替换执行的次数。

那么关于preg_replace("/[^0-9,.]/", "", $str1),这个表达式的意思就是,匹配除了0-9间的数字以及逗号和点号以外的字符,并将这些字符替换为空即删除即可。

最后关于正则表达式,我在这里给大家推荐一个视频教程《正则表达式极速入门》,包你快速入门。

The above is the detailed content of Remove non-numeric characters except comma and dot via PHP regex. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn