PHP提取字符串中数字的方法

WBOY
Release: 2016-06-20 13:05:07
Original
3718 people have browsed it

PHP提取字符串中数字的方法

有时候我们在PHP开发中需要在一串字符串中将所有的数字提取出来,研究了一下发现方法还挺多,值得记录一下。

对如何使用PHP将字符串中的数字提取出来的功能做了一个小总结,总结三种方法如下:

1、使用正则表达式:

<span style="font-size: 14px;">function findNum($str=''){</span><br />	$str=trim($str);<br />	if(empty($str)){return '';}<br />	$reg='/(\d{3}(\.\d+)?)/is';//匹配数字的正则表达式<br />	preg_match_all($reg,$str,$result);<br />	if(is_array($result)&&!empty($result)&&!empty($result[1])&&!empty($result[1][0])){<br />		return $result[1][0];<br />	}<br />	return '';<br /><p>}<span style="font-size: 14px;">
Copy after login

2、使用in_array方法:

<span style="font-size: 14px;">function findNum($str=''){</span><br />	$str=trim($str);<br />	if(empty($str)){return '';}<br />	$temp=array('1','2','3','4','5','6','7','8','9','0');<br />	$result='';<br />	for($i=0;$i<strlen($str);$i++){<br />		if(in_array($str[$i],$temp)){<br />			$result.=$str[$i];<br />		}<br />	}<br />	return $result;<br /><p>}<span style="font-size: 14px;">
Copy after login

3、使用is_numeric函数:

<span style="font-size: 14px;">function findNum($str=''){</span><br />	$str=trim($str);<br />	if(empty($str)){return '';}<br />	$result='';<br />	for($i=0;$i<strlen($str);$i++){<br />		if(is_numeric($str[$i])){<br />			$result.=$str[$i];<br />		}<br />	}<br />	return $result;<br />}
Copy after login


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!