Home  >  Article  >  Backend Development  >  php结合正则获取字符串中数字_PHP教程

php结合正则获取字符串中数字_PHP教程

WBOY
WBOYOriginal
2016-07-13 09:49:54914browse

php结合正则获取字符串中数字

   这篇文章主要给大家汇总介绍了php结合正则获取字符串中数字的几种方法,十分的简单实用,有需要的小伙伴可以参考下。

  php结合正则获取字符串中数字

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

$patterns = "/\d+/"; //第一种

//$patterns = "/\d/"; //第二种

$strs="left:0px;top:202px;width:90px;height:30px";

preg_match_all($patterns,$strs,$arr);

print_r($arr);

 

/***************运行结果*********************/

//第一种

Array

(

[0] => Array

(

[0] => 0

[1] => 202

[2] => 90

[3] => 30

)

)

//第二种

Array

(

[0] => Array

(

[0] => 0

[1] => 2

[2] => 0

[3] => 2

[4] => 9

[5] => 0

[6] => 3

[7] => 0

)

)

  php 获取指定字符串的数字 $a="时代发123生的12345678发生的"; 给一个函数能抓取到$a中的数字12345678,如果没有,则返回0

  要写好函数,

  1.只匹配长度位8的数字

  2.如果找到则返回改数字,如果没有则返回0

  ?

1

2

3

function a($str){

return preg_match('/([0-9]{8})/',$str,$a) ? $a[1] : 0;

}

  在网上搜索到这个测试一下发现还可以,但是如果字符长度不d{4} 不定长就不行了

  ?

1

2

3

4

5

6

7

8

9

function findNum($str=''){

if(empty($str)){return '';}

$reg='/(\d{4}(\.\d+)?)/is';//匹配数字的正则表达式

preg_match_all($reg,$str,$result);

if(is_array($result)&&!empty($result)&&!empty($result[1])&&!empty($result[1][0])){

return $result[1][0];

}

return '';

}

  后来又发现知道中有一个

  ?

1

2

$str=trim($str);

if (preg_match('|(\d+)|',$str,$r)) return $r[1];

  发现这个可以获取任意连续长度的数字了,当然在网上还看到很多,但有一个可以了所以就没有再测试了。

  以上所述就是本文的全部内容了,希望大家能够喜欢。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1018923.htmlTechArticlephp结合正则获取字符串中数字 这篇文章主要给大家汇总介绍了php结合正则获取字符串中数字的几种方法,十分的简单实用,有需要的小伙伴...
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