使用PHP从字符串中获取数字

时间:2012-06-28 11:17:13

标签: php regex

我有字符串:

$one = 'foo bar 4 baz (5 qux quux)';
$two = 'bar baz 2 bar';
$three =  'qux bar 12 quux (3 foo)';
$four = 'foo baz 3 bar (13 quux foo)';

如何在这些字符串中找到数字?

也许有功能:

function numbers($string){

    // ???

    $first = ?;
    $second = ?;
}

例如:

function numbers($one){

    // ???

    $first = 4;
    $second = 5;
}

function numbers($two){

    // ???

    $first = 2;
    $second = NULL;
}

最好的办法可能就是正则表达式,但我怎么能用这个作为我的例子呢?也许没有正则表达式?

3 个答案:

答案 0 :(得分:27)

您可以使用regular expressions\d escape sequence将匹配主题字符串中的所有数字。

例如:

<?php

function get_numerics ($str) {
    preg_match_all('/\d+/', $str, $matches);
    return $matches[0];
}

$one = 'foo bar 4 baz (5 qux quux)';
$two = 'bar baz 2 bar';
$three = 'qux bar 12 quux (3 foo)';
$four = 'foo baz 3 bar (13 quux foo)';

print_r(get_numerics($one));
print_r(get_numerics($two));
print_r(get_numerics($three));
print_r(get_numerics($four));

https://3v4l.org/DiDBL

答案 1 :(得分:6)

你可以这样做:

$str = 'string that contains numbers';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);

答案 2 :(得分:5)

这是我的尝试没有正则表达式

function getNumbers($str) {
    $result = array();

    // Check each character.
    for($i = 0, $len = strlen($str); $i < $len; $i++) {
        if(is_numeric($str[$i])) {
            $result[] = $str[$i];
        }
    }

    return $result;
}

$one = 'one two 4 three (5 four five)';
$two = 'one two 2 three';
$three =  'one two 12 three (3 four)';
$four = 'one two 3 three (13 four five)';

var_dump(getNumbers($one));
var_dump(getNumbers($two));
var_dump(getNumbers($three));
var_dump(getNumbers($four));

//输出:

array(2) {
  [0]=>
  string(1) "4"
  [1]=>
  string(1) "5"
}

array(1) {
  [0]=>
  string(1) "2"
}

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}

array(3) {
  [0]=>
  string(1) "3"
  [1]=>
  string(1) "1"
  [2]=>
  string(1) "3"
}