在php中过滤掉字符串中的数字 [英] Filter out numbers in a string in php

查看:606
本文介绍了在php中过滤掉字符串中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这些文本"x34","150px","650dpi","e3r4t5" ...我怎么只能得到数字?我的意思是我想要34,150,650,345没有其他字符.我的意思是将字符串中的数字变成一个变量.

assuming i have these texts 'x34' , '150px' , '650dpi' , 'e3r4t5' ... how can i get only numbers ? i mean i want 34 , 150 , 650 , 345 without any other character . i mean get the numbers this string has into one variable .

推荐答案

很抱歉,您迟来加入潮流,而不是使用Regex,建议您使用PHP的内置函数,该函数可能比Regex快.

Sorry for joining the bandwagon late, rather than using Regex, I would suggest you use PHP's built in functions, which may be faster than Regex.

filter_var

过滤器的标志

例如从给定的字符串中获取数字

e.g. to get just numbers from the given string

<?php
$a = '!a-b.c3@j+dk9.0$3e8`~]\]2';
$number = str_replace(['+', '-'], '', filter_var($a, FILTER_SANITIZE_NUMBER_INT));
// Output is 390382
?>

为了对您的问题遵循更严格的标准,我更新了答案以提供更好的结果.

To adhere to more strict standards for your question, I have updated my answer to give a better result.

我添加了str_replace,因为FILTER_SANITIZE_NUMBER_FLOATINT标志不会从字符串中删除+-字符,因为它们是PHP异常规则的一部分.

I have added str_replace, as FILTER_SANITIZE_NUMBER_FLOAT or INT flag will not strip + and - chars from the string, because they are part of PHP's exception rule.

尽管它使过滤器过长,但现在失败或出现意外结果的可能性较小,这将比REGEX更快.

Though it has made the filter bit long, but it's now has less chance of failing or giving you unexpected results, and this will be faster than REGEX.

1:意识到使用FILTER_SANITIZE_NUMBER_FLOAT,PHP不会可选地删除这些字符 .,eE,因此,请使用FILTER_SANITIZE_NUMBER_INT

1: Realized that with FILTER_SANITIZE_NUMBER_FLOAT, PHP won't strip these characters optionally .,eE, hence to get just pure numbers kindly use FILTER_SANITIZE_NUMBER_INT

2 :如果您的PHP版本低于 5.4 ,请使用array('+', '-')而不是短数组语法['+', '-'].

2: If you have a PHP version less than 5.4, then kindly use array('+', '-') instead of the short array syntax ['+', '-'].

这篇关于在php中过滤掉字符串中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆